Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure DevOps reports PowerShell task as passed even with non-0 exit code

In Azure DevOps I have a task to run a PowerShell script. In certain scenarios, the script should exit with a non-0 code, causing the task to be reported as failed. However, Azure DevOps reports the task as passed regardless.

This is a problem because I have a subsequent job that should run if this job fails, but that is not happening because of the false positive.

enter image description here

The relevant part of the script shows that, in the case of the screenshot, an exit code of 1 was detected, which should result in the script exiting in error.

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

The task is run as part of a deployment job, and I do have the option failOnStandardError set to 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

How can I make Azure DevOps honour my exit codes?

like image 605
David Gard Avatar asked Aug 20 '20 15:08

David Gard


People also ask

What is PowerShell exited with code 1?

Powershell Exit Code 1 = Get Output Failed.

How do I get the exit code in PowerShell?

Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.


1 Answers

It seems that the Azure PowerShell task has an issue capturing the exit code from a script file, it works fine with the inline scripts. You can report this problem to Microsoft development team. Hope they will provide a fix soon.

However, you can use either of below workarounds to fix it.

1, Use [Environment]::Exit($exitCode) instead of exit. See below:

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

2, Use logging command ##vso[task.complete result=Failed;]Failed to manually fail the task if the exitCode is non-0. See below:

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
like image 152
Levi Lu-MSFT Avatar answered Oct 06 '22 23:10

Levi Lu-MSFT