Partilhar via


PowerShell@2 - Tarefa PowerShell v2

Use esta tarefa para executar um script do PowerShell no Linux, macOS ou Windows.

Observação

Por padrão, o PowerShell v2 usa o PowerShell Core para agentes Linux e o Windows PowerShell para agentes Windows. Para usar a versão mais recente do PowerShell em agentes do Windows, defina o parâmetro pwsh como true. Em vez disso, o PowerShell Core será usado.

Sintaxe

# PowerShell v2
# Run a PowerShell script on Linux, macOS, or Windows.
- task: PowerShell@2
  inputs:
    #targetType: 'filePath' # 'filePath' | 'inline'. Type. Default: filePath.
    filePath: # string. Required when targetType = filePath. Script Path. 
    #arguments: # string. Optional. Use when targetType = filePath. Arguments. 
    #script: # string. Required when targetType = inline. Script. 
  # Preference Variables
    #errorActionPreference: 'stop' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. ErrorActionPreference. Default: stop.
    #warningPreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. WarningPreference. Default: default.
    #informationPreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. InformationPreference. Default: default.
    #verbosePreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. VerbosePreference. Default: default.
    #debugPreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. DebugPreference. Default: default.
    #progressPreference: 'silentlyContinue' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. ProgressPreference. Default: silentlyContinue.
  # Advanced
    #failOnStderr: false # boolean. Fail on Standard Error. Default: false.
    #showWarnings: false # boolean. Show warnings as Azure DevOps warnings. Default: false.
    #ignoreLASTEXITCODE: false # boolean. Ignore $LASTEXITCODE. Default: false.
    #pwsh: false # boolean. Use PowerShell Core. Default: false.
    #workingDirectory: # string. Working Directory. 
    #runScriptInSeparateScope: false # boolean. Run script in the separate scope. Default: false.
# PowerShell v2
# Run a PowerShell script on Linux, macOS, or Windows.
- task: PowerShell@2
  inputs:
    #targetType: 'filePath' # 'filePath' | 'inline'. Type. Default: filePath.
    filePath: # string. Required when targetType = filePath. Script Path. 
    #arguments: # string. Optional. Use when targetType = filePath. Arguments. 
    #script: # string. Required when targetType = inline. Script. 
  # Preference Variables
    #errorActionPreference: 'stop' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. ErrorActionPreference. Default: stop.
    #warningPreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. WarningPreference. Default: default.
    #informationPreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. InformationPreference. Default: default.
    #verbosePreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. VerbosePreference. Default: default.
    #debugPreference: 'default' # 'default' | 'stop' | 'continue' | 'silentlyContinue'. DebugPreference. Default: default.
  # Advanced
    #failOnStderr: false # boolean. Fail on Standard Error. Default: false.
    #showWarnings: false # boolean. Show warnings as Azure DevOps warnings. Default: false.
    #ignoreLASTEXITCODE: false # boolean. Ignore $LASTEXITCODE. Default: false.
    #pwsh: false # boolean. Use PowerShell Core. Default: false.
    #workingDirectory: # string. Working Directory. 
    #runScriptInSeparateScope: false # boolean. Run script in the separate scope. Default: false.
# PowerShell v2
# Run a PowerShell script on Linux, macOS, or Windows.
- task: PowerShell@2
  inputs:
    #targetType: 'filePath' # 'filePath' | 'inline'. Type. Default: filePath.
    filePath: # string. Required when targetType = filePath. Script Path. 
    #arguments: # string. Optional. Use when targetType = filePath. Arguments. 
    #script: # string. Required when targetType = inline. Script. 
    #errorActionPreference: 'stop' # 'stop' | 'continue' | 'silentlyContinue'. ErrorActionPreference. Default: stop.
  # Advanced
    #failOnStderr: false # boolean. Fail on Standard Error. Default: false.
    #showWarnings: false # boolean. Show warnings as Azure DevOps warnings. Default: false.
    #ignoreLASTEXITCODE: false # boolean. Ignore $LASTEXITCODE. Default: false.
    #pwsh: false # boolean. Use PowerShell Core. Default: false.
    #workingDirectory: # string. Working Directory.
# PowerShell v2
# Run a PowerShell script on Linux, macOS, or Windows.
- task: PowerShell@2
  inputs:
    #targetType: 'filePath' # 'filePath' | 'inline'. Type. Default: filePath.
    filePath: # string. Required when targetType = filePath. Script Path. 
    #arguments: # string. Optional. Use when targetType = filePath. Arguments. 
    #script: # string. Required when targetType = inline. Script. 
    #errorActionPreference: 'stop' # 'stop' | 'continue' | 'silentlyContinue'. ErrorActionPreference. Default: stop.
  # Advanced
    #failOnStderr: false # boolean. Fail on Standard Error. Default: false.
    #ignoreLASTEXITCODE: false # boolean. Ignore $LASTEXITCODE. Default: false.
    #pwsh: false # boolean. Use PowerShell Core. Default: false.
    #workingDirectory: # string. Working Directory.

Insumos

targetType - Tipo
string. Valores permitidos: filePath (Caminho do arquivo), inline. Valor padrão: filePath.

Especifica o tipo de script para a tarefa a ser executada: um script embutido ou um caminho para um arquivo .ps1.


filePath - caminho do script
string. Necessário quando targetType = filePath.

Especifica o caminho do script a ser executado. Deve ser um caminho totalmente qualificado ou relativo a $(System.DefaultWorkingDirectory).


arguments - Argumentos
string. Opcional. Use quando targetType = filePath.

Especifica os argumentos passados para o script do PowerShell. Os argumentos podem ser parâmetros ordinais ou parâmetros nomeados. Por exemplo, -Name someName -Path -Value "Some long string value".

arguments não é usado quando targetType está definido como inline.


script - Guião
string. Necessário quando targetType = inline. Valor padrão: # Write your PowerShell commands here.\n\nWrite-Host "Hello World".

Especifica o conteúdo do script. O comprimento máximo de script embutido suportado é de 20000 caracteres. Use um script de um arquivo se quiser usar um script mais longo.


errorActionPreference - ErrorActionPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor padrão: stop.

Precede a linha $ErrorActionPreference = 'VALUE' na parte superior do script.


errorActionPreference - ErrorActionPreference
string. Valores permitidos: stop, continue, silentlyContinue. Valor padrão: stop.

Precede a linha $ErrorActionPreference = 'VALUE' na parte superior do script.


warningPreference - WarningPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor padrão: default.

Quando não estiver definido como Default, precede a linha $WarningPreference = 'VALUE' na parte superior do script.


informationPreference - InformaçãoPreferência
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor padrão: default.

Quando não estiver definido como Default, precede a linha $InformationPreference = 'VALUE' na parte superior do script.


verbosePreference - VerbosePreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor padrão: default.

Quando não estiver definido como Default, precede a linha $VerbosePreference = 'VALUE' na parte superior do script.


debugPreference - DebugPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor padrão: default.

Quando não estiver definido como Default, precede a linha $DebugPreference = 'VALUE' na parte superior do script.


progressPreference - ProgressPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor padrão: silentlyContinue.

Quando não estiver definido como Default, precede a linha $ProgressPreference = 'VALUE' na parte superior do script.


failOnStderr - falha no erro padrão
boolean. Valor padrão: false.

Se o valor desse booleano for true, a tarefa falhará se algum erro for gravado no pipeline de erros ou se algum dado for gravado no fluxo de erro padrão. Caso contrário, a tarefa depende do código de saída para determinar a falha.


showWarnings - Mostrar avisos como avisos do Azure DevOps
boolean. Valor padrão: false.

Se o valor estiver definido como truee o script escrever avisos, os avisos aparecerão como avisos nos logs de pipeline.


ignoreLASTEXITCODE - Ignorar $LASTEXITCODE
boolean. Valor padrão: false.

Se o valor estiver definido como false, a linha if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE } será acrescentada ao final do script. Isso fará com que o último código de saída de um comando externo seja propagado como o código de saída de powershell. Caso contrário, a linha não será anexada ao final do script.


pwsh - Usar o PowerShell Core
boolean. Valor padrão: false.

Se isso for verdade, as tarefas executadas em agentes do Windows usarão pwsh.exe do seu caminho em vez de powershell.exe.


workingDirectory - Diretório de Trabalho
string.

Especifica o diretório de trabalho onde o script é executado. Se um valor não for especificado, o diretório de trabalho será $(Build.SourcesDirectory).


runScriptInSeparateScope - Executar script no escopo separado
boolean. Valor padrão: false.

Essa entrada permite executar scripts do PowerShell usando & operador em vez do .padrão. Se essa entrada estiver definida como true, o script será executado em um escopo separado e as variáveis do PowerShell com escopo global não serão atualizadas.


Opções de controlo de tarefas

Todas as tarefas têm opções de controle, além de suas entradas de tarefas. Para obter mais informações, consulte Opções de controle de e propriedades de tarefas comuns.

Variáveis de saída

Nenhum.

Observações

Cada sessão do PowerShell dura apenas a duração do trabalho em que é executada. As tarefas que dependem do que foi inicializado devem estar no mesmo trabalho que o bootstrap.

Atalhos de tarefas

PowerShell@2 tem dois atalhos no YAML: steps.powershell e steps.pwsh.

  • powershell é executado usando o Windows PowerShell (no Windows) ou o pwsh (Linux e macOS).
  • pwsh executa o PowerShell Core, a edição multiplataforma do PowerShell baseada no .NET Core.
steps:
- powershell: # Run a script in Windows PowerShell on Windows, and pwsh on Linux and macOS.
- pwsh: # Run a script in PowerShell Core on Windows, macOS, and Linux.

Defina uma variável para que possa ser lida por scripts e tarefas subsequentes

Para saber mais sobre como definir variáveis de compilação em um script, consulte Definir e modificar suas variáveis de compilação em um script.

Para saber mais sobre como definir variáveis de liberação em um script, consulte Definir e modificar suas variáveis de liberação em um script.

Passando segredos de pipeline no script, mas o segredo não é mascarado nos logs de pipeline

Lembre-se de que o PowerShell corta mensagens de erro, portanto, se você usar segredos de pipeline em um script, os segredos poderão ser cortados e expostos. Por exemplo, no script embutido abaixo:

./script.ps1 --arg1 value1 --arg2 <some_secret_which_will_be_masked_here>

Pode haver uma exceção como: At <path_to_temp_script_file>:4 char:3:

+   ./script.ps1 --arg1 value1 --arg2 <unmasked_part_of_original_secret> ...
+   ~~~~~~~~~~
    + <Additional exception details>

Para evitar esse problema, você pode lidar com essas exceções em um nível de script ou evitar casos em que segredos de pipeline podem aparecer em linhas de código-fonte em mensagens de erro.

Exemplos

Invocar um script a partir de um ficheiro

A seguir está um arquivo PowerShell de exemplo chamado test.ps1 localizado na raiz do repositório.

Write-Host "Hello World from $Env:AGENT_NAME."
Write-Host "My ID is $Env:AGENT_ID."
Write-Host "AGENT_WORKFOLDER contents:"
gci $Env:AGENT_WORKFOLDER
Write-Host "AGENT_BUILDDIRECTORY contents:"
gci $Env:AGENT_BUILDDIRECTORY
Write-Host "BUILD_SOURCESDIRECTORY contents:"
gci $Env:BUILD_SOURCESDIRECTORY
Write-Host "Over and out."

Você pode invocar esse script em seu pipeline assim.

steps:
- task: PowerShell@2
  inputs:
    targetType: 'filePath'
    filePath: 'test.ps1'

Escreva um aviso

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: Write-Host "##vso[task.LogIssue type=warning;]This is the warning"
    # Writes a warning to build summary and to log in yellow text

Escrever um erro

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: Write-Host "##vso[task.LogIssue type=error;]This is the error"
    # Writes an error to build summary and to log in red text

Se você quiser que esse erro falhe na compilação, adicione exit 1 ao script.

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      Write-Host "##vso[task.LogIssue type=error;]This is the error"
      exit 1
    # Writes an error to build summary and to log in red text

Chamar script do PowerShell com vários argumentos

Criar script do PowerShell test2.ps1:

param ($input1, $input2)
Write-Host "$input1 $input2"

No seu pipeline YAML, ligue:

- task: PowerShell@2
  inputs:
    targetType: 'filePath'
    filePath: $(System.DefaultWorkingDirectory)\test2.ps1
    arguments: > # Use this to avoid newline characters in multiline string
      -input1 "Hello"
      -input2 "World"
  displayName: 'Print Hello World'

Requerimentos

Requisito Descrição
Tipos de pipeline YAML, Construção clássica, Versão clássica
Funciona em Agente, DeploymentGroup
Exigências Nenhum
Capacidades Esta tarefa não satisfaz quaisquer exigências para tarefas subsequentes no trabalho.
Restrições de comando Qualquer
Variáveis configuráveis Qualquer
Versão do agente 2.115.0 ou superior
Categoria de tarefa Utilidade

Ver também