PowerShell@2 - Tarefa do PowerShell v2

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

Nota

Por predefinição, o PowerShell v2 utiliza o PowerShell Core para agentes do Linux e Windows PowerShell para agentes do Windows. Para utilizar a versão mais recente do PowerShell em agentes do Windows, defina o pwsh parâmetro como true. Em seguida, será utilizado o PowerShell Core.

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 Ficheiro), inline. Valor predefinido: filePath.

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


filePath - Caminho do Script
string. Necessário quando targetType = filePath.

Especifica o caminho do script a executar. Tem de ser um caminho completamente qualificado ou relativo a $(System.DefaultWorkingDirectory).


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

Especifica os argumentos transmitidos 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 é utilizado quando targetType está definido como inline.


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

Especifica o conteúdo do script. O comprimento máximo do script inline suportado é de 20 000 carateres. Utilize um script de um ficheiro se quiser utilizar um script mais longo.


script - Script
string. Necessário quando targetType = inline. Valor predefinido: # 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 do script inline suportado é de 20 000 carateres. Utilize um script de um ficheiro se quiser utilizar um script mais longo.


errorActionPreference - ErrorActionPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor predefinido: stop.

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


errorActionPreference - ErrorActionPreference
string. Valores permitidos: stop, , continuesilentlyContinue. Valor predefinido: stop.

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


warningPreference - AvisoPreferência
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor predefinido: default.

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


informationPreference - InformationPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor predefinido: default.

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


verbosePreference - VerbosePreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor predefinido: default.

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


debugPreference - DepurarPreferência
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor predefinido: default.

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


progressPreference - ProgressPreference
string. Valores permitidos: default, stop, continue, silentlyContinue. Valor predefinido: silentlyContinue.

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


failOnStderr - Falha no Erro Padrão
boolean. Valor predefinido: false.

Se o valor deste valor booleano for true, a tarefa falhará se forem escritos erros no pipeline de erros ou se forem escritos dados 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 predefinido: false.

Se o valor estiver definido como truee o script escrever avisos, os avisos serão apresentados como avisos nos registos do Pipeline.


ignoreLASTEXITCODE - Ignorar $LASTEXITCODE
boolean. Valor predefinido: false.

Se o valor estiver definido como false, a linha if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE } é anexada ao fim do script. Isto 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 é acrescentada ao fim do script.


pwsh - Utilizar o PowerShell Core
boolean. Valor predefinido: false.

Se for verdade, as tarefas em execução nos agentes do Windows utilizarão pwsh.exe a partir 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 não for especificado um valor, o diretório de trabalho é $(Build.SourcesDirectory).


runScriptInSeparateScope - Executar script no âmbito separado
boolean. Valor predefinido: false.

Esta entrada permite executar scripts do PowerShell com & o operador em vez do predefinido .. Se esta entrada estiver definida como true, o script será executado num âmbito separado e as variáveis do PowerShell com âmbito global não serão atualizadas.


Opções de controlo de tarefas

Todas as tarefas têm opções de controlo para além das entradas de tarefas. Para obter mais informações, veja Opções de controlo e propriedades de tarefas comuns.

Variáveis de saída

Nenhum.

Observações

Cada sessão do PowerShell dura apenas a duração da tarefa em que é executada. As tarefas que dependem do que foi iniciado têm de estar na mesma tarefa que o bootstrap.

Atalhos de tarefas

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

  • powershellé executado com Windows PowerShell (no Windows) ou pwsh (Linux e macOS).
  • pwsh executa o PowerShell Core, a edição multiplataformas do PowerShell criada com base 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 possa ser lida por scripts e tarefas subsequentes

Para saber mais sobre como definir variáveis de compilação num script, veja Definir e modificar as variáveis de compilação num script.

Para saber mais sobre como definir variáveis de versão num script, veja Definir e modificar as variáveis de versão num script.

Transmitir segredos do pipeline no script, mas o segredo não está mascarado nos registos do pipeline

Tenha em atenção que o PowerShell corta as mensagens de erro, por isso, se utilizar segredos de pipeline num script, os segredos podem ser cortados e expostos. Por exemplo, no script inline abaixo:

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

Pode existir 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 este problema, pode processar estas exceções ao nível do script ou evitar casos em que os segredos do pipeline possam aparecer nas linhas de código fonte nas mensagens de erro.

Exemplos

Invocar um script a partir de um ficheiro

Segue-se um ficheiro do PowerShell de exemplo com o nome test.ps1 localizado na raiz do seu 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."

Pode invocar este script no seu pipeline desta forma.

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

Escrever 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 quiser que este 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 test2.ps1do 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 Description
Tipos de pipeline YAML, Compilação clássica, Versão clássica
É executado em Agent, DeploymentGroup
Exigências Nenhuma
Capacidades Esta tarefa não satisfaz quaisquer exigências para tarefas subsequentes na tarefa.
Restrições de comandos Qualquer
Variáveis de definição Qualquer
Versão do agente 2.115.0 ou superior
Categoria da tarefa Utilitário

Ver também