Поделиться через


определение steps.powershell

Шаг powershell запускает скрипт с помощью Windows PowerShell (в Windows) или pwsh (Linux и macOS).

steps:
- powershell: string # Required as first property. Inline PowerShell script.
  errorActionPreference: string # Unless otherwise specified, the error action preference defaults to the value stop. See the following section for more information.
  failOnStderr: string # Fail the task if output is sent to Stderr?
  ignoreLASTEXITCODE: string # Check the final exit code of the script to determine whether the step succeeded?
  workingDirectory: string # Start the script with this working directory.
  condition: string # Evaluate this condition expression to determine whether to run this task.
  continueOnError: boolean # Continue running even on failure?
  displayName: string # Human-readable name for the task.
  target: string | target # Environment in which to run this task.
  enabled: boolean # Run this task when the job runs?
  env: # Variables to map into the process's environment.
    string: string # Name/value pairs
  name: string # ID of the step.
  timeoutInMinutes: string # Time to wait for this task to complete before the server kills it.
  retryCountOnTaskFailure: string # Number of retries if the task fails.
steps:
- powershell: string # Required as first property. Inline PowerShell script.
  errorActionPreference: string # Unless otherwise specified, the error action preference defaults to the value stop. See the following section for more information.
  failOnStderr: string # Fail the task if output is sent to Stderr?
  ignoreLASTEXITCODE: string # Check the final exit code of the script to determine whether the step succeeded?
  workingDirectory: string # Start the script with this working directory.
  condition: string # Evaluate this condition expression to determine whether to run this task.
  continueOnError: boolean # Continue running even on failure?
  displayName: string # Human-readable name for the task.
  target: string | target # Environment in which to run this task.
  enabled: boolean # Run this task when the job runs?
  env: # Variables to map into the process's environment.
    string: string # Name/value pairs
  name: string # ID of the step.
  timeoutInMinutes: string # Time to wait for this task to complete before the server kills it.

Определения, ссылающиеся на это определение: шаги

Свойства

строка powershell. Обязательный в качестве первого свойства.
встроенный скрипт PowerShell.

строка errorActionPreference.
, если иное не указано, параметр действия ошибки по умолчанию используется для остановки значения. Дополнительные сведения см. в следующем разделе.

строка failOnStderr.
сбой задачи, если выходные данные отправляются в Stderr?

строка ignoreLASTEXITCODE.
Проверьте окончательный код выхода скрипта, чтобы определить, выполнен ли шаг успешно?

строка workingDirectory.
Запустите скрипт с помощью этого рабочего каталога.

строка condition.
оценить это выражение условия, чтобы определить, следует ли выполнять эту задачу.

continueOnError логические.
Продолжить работу даже при сбое?

строка displayName.
имя, доступное для чтения для задачи.

target целевой.
среда, в которой выполняется эта задача.

enabled логические.
запустить эту задачу при выполнении задания?

env словарь строк.
Переменные для сопоставления с средой процесса.

строка name.
идентификатор шага. Допустимые значения: [-_A-Za-z0-9]*.

строка timeoutInMinutes.
время ожидания завершения этой задачи до того, как сервер убьет его.

Примечание.

Конвейеры могут быть настроены с временем ожидания уровня задания. Если интервал времени ожидания задания истекает до завершения шага, выполнение задания (включая шаг) завершается, даже если шаг настроен с более длинным интервалом timeoutInMinutes. Дополнительные сведения см. в разделе "Время ожидания".

строка retryCountOnTaskFailure.
число повторных попыток, если задача завершается ошибкой.

Замечания

Ключевое слово powershell — это ярлык для задачи PowerShell. Задача выполняет скрипт с помощью Windows PowerShell (в Windows) или pwsh (Linux и macOS).

Каждый сеанс PowerShell длится только в течение всего задания, в котором он выполняется. Задачи, зависящие от начальной загрузки, должны находиться в том же задании, что и начальная загрузка.

Дополнительные сведения об условиях и времени ожидания.

Предпочтения действия ошибки

Если иное не указано, параметр действия ошибки по умолчанию соответствует значению stop, а строка $ErrorActionPreference = 'stop' добавляется в начало скрипта.

Если для параметра действия ошибки задано значение остановки, ошибки вызывают завершение задачи PowerShell и возврат ненулевого кода выхода. Задача также помечена как сбой.

errorActionPreference: stop | continue | silentlyContinue
steps:
- powershell: |
    Write-Error 'Uh oh, an error occurred'
    Write-Host 'Trying again...'
  displayName: Error action preference
  errorActionPreference: continue

Игнорировать код последнего выхода

Последний код выхода, возвращенный из скрипта, по умолчанию проверяется. Код, отличный от нуля, указывает на сбой шага, в котором система добавляет скрипт с помощью:

if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE }

Если это поведение не требуется, укажите ignoreLASTEXITCODE: true.

ignoreLASTEXITCODE: boolean
steps:
- powershell: git nosuchcommand
  displayName: Ignore last exit code
  ignoreLASTEXITCODE: true

Дополнительные сведения об условиях и времени ожидания.

Примеры

steps:
- powershell: Write-Host Hello $Env:name
  displayName: Say hello
  name: firstStep
  workingDirectory: $(build.sourcesDirectory)
  failOnStderr: true
  env:
    name: Microsoft

См. также

  • задача PowerShell
  • Дополнительные сведения об условиях и времени ожидания