PowerShell@2 - Tarefa do PowerShell v2

Use essa 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 do Linux e Windows PowerShell para agentes do Windows. Para usar a versão mais recente do PowerShell em agentes do Windows, defina o pwsh parâmetro como true. Em vez disso, o PowerShell Core será usado.

Syntax

# 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.
# PowerShell v2
# Run a PowerShell script on Windows, macOS, or Linux.
- 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.

Entradas

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 .ps1 arquivo.


filePath - Caminho do Script
string. Obrigató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".

argumentsnão é usado quando é definido inlinecomo targetType .


script - Script
string. Obrigató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 com suporte é de 20000 caracteres. Use um script de um arquivo se quiser usar um script mais longo.


script - Script
string. Obrigatório quando targetType = inline. Valor padrão: # Write your powershell commands here.\n\nWrite-Host "Hello World"\n\n# Use the environment variables input below to pass secret variables to this script..

Especifica o conteúdo do script. O comprimento máximo de script embutido com suporte é 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.

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


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

Anexa 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 definido Defaultcomo , acrescenta a linha $WarningPreference = 'VALUE' na parte superior do script.


informationPreference - InformationPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor padrão: default.

Quando não definido Defaultcomo , acrescenta 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 definido Defaultcomo , acrescenta 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 definido Defaultcomo , acrescenta 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 definido Defaultcomo , acrescenta a linha $ProgressPreference = 'VALUE' na parte superior do script.


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

Se o valor desse booliano for true, a tarefa falhará se algum erro for gravado no pipeline de erro 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 for definido truecomo e o script gravar avisos, os avisos aparecerão como avisos nos logs do pipeline.


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

Se o valor for definido falsecomo , 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á acrescentada ao final do script.


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

Se isso for verdadeiro, as tarefas em execução em agentes do Windows usarão pwsh.exe do caminho em vez de powershell.exe.


workingDirectory - Diretório de Trabalho
string.

Especifica o diretório de trabalho em que 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 a execução de scripts do PowerShell usando & o operador em vez do padrão .. Se essa entrada for definida truecomo , 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 controle da tarefa

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

Variáveis de saída

Nenhum.

Comentários

Cada sessão do PowerShell dura apenas enquanto o trabalho é executado. As tarefas que dependem do que foi inicializado devem estar no mesmo trabalho que a inicialização.

Atalhos de tarefa

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

  • powershellé executado usando Windows PowerShell (no Windows) ou pwsh (Linux e macOS).
  • O pwsh executa o PowerShell Core, a edição multiplataforma do PowerShell criada 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.

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

Para saber mais sobre como definir variáveis de build em um script, confira Definir e modificar suas variáveis de build em um script.

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

Passar 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 possam aparecer em linhas de código-fonte dentro de mensagens de erro.

Exemplos

Invocar um script de um arquivo

Veja a seguir um arquivo de exemplo do PowerShell 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'

Gravar 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

Gravar 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 no build, 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 um test2.ps1 de script do PowerShell:

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

No pipeline YAML, chame:

- 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'

Requisitos

Requisito Descrição
Tipos de pipeline YAML, build clássico, versão clássica
Executa em Agent, DeploymentGroup
Demandas Nenhum
Funcionalidades Essa tarefa não atende a nenhuma demanda 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 da tarefa Utilitário

Confira também