即使没有非零退出代码,Azure DevOps也会报告PowerShell任务已通过

问题描述

在Azure DevOps中,我有一个运行PowerShell脚本的任务。在某些情况下,脚本应以非0代码退出,从而导致任务报告为失败。但是,无论如何,Azure DevOps都会报告任务已通过。

这是一个问题,因为如果此作业失败,我有一个后续的作业应运行,但由于误报而不会发生。

enter image description here

脚本的相关部分显示,在截屏的情况下,检测到退出代码1,这将导致脚本错误退出。

if ($exitCode -ne 0)
{
    Write-Output ("[Error] Failing task since return code was {0} while expected 0." -f $exitCode)
}
exit $exitCode

该任务作为deployment作业的一部分运行,我确实将选项failOnStandardError设置为true

- task: AzurePowerShell@5
  displayName: Check Function App Version
  inputs:
    azureSubscription: ${{ parameters.serviceConnectionName }}
    scriptType: FilePath
    scriptPath: ${{ parameters.scriptsArtefactPath }}/Test-FunctionAppVersion.ps1
    scriptArguments: -Uri ${{ parameters.healthCheckUri }} -AuthHeaderName Authorization -AuthHeaderValue "$(healthCheckAuthHeaderValue)"
    failOnStandardError: true
    azurePowerShellVersion: LatestVersion
    pwsh: true

如何使Azure DevOps遵守我的退出代码?

解决方法

Azure PowerShell任务似乎在捕获脚本文件中的退出代码时遇到问题,它与内联脚本一起正常工作。您可以report this problem前往Microsoft开发团队。希望他们能尽快提供修复。

但是,您可以使用以下两种解决方法之一进行修复。

1,使用[Environment]::Exit($exitCode)代替exit。见下文:

if ($exitCode -ne 0)
{
    Write-Output ("[Error] Failing task since return code was {0} while expected 0." -f $exitCode)
}
[Environment]::Exit($exitCode)

2,如果exitCode非0,请使用logging command ##vso[task.complete result=Failed;]Failed手动使任务失败。见下文:

if ($exitCode -ne 0)
{
    Write-Output ("[Error] Failing task since return code was {0} while expected 0." -f $exitCode)
    Write-Host "##vso[task.complete result=Failed;]Failed"
}
exit $exitCode

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...