Why are my PowerShell exit codes always “0”?

This is a known issue with PowerShell. Executing a script with -file returns an exit code of 0 when it shouldn’t.

(Update: The links below no longer work. Please look for, or report, this problem on PowerShell: Hot (1454 ideas) – Windows Server)

  • https://connect.microsoft.com/PowerShell/feedback/details/777375/powershell-exe-does-not-set-an-exit-code-when-file-is-used

  • https://connect.microsoft.com/PowerShell/feedback/details/750653/powershell-exe-doesn-t-return-correct-exit-codes-when-using-the-file-option

Since using -command wasn’t working for you, you could try adding a trap at the top of the script:

trap
{
    write-output $_
    ##teamcity[buildStatus status="FAILURE" ]
    exit 1
}

The above should result in a proper exit code when an exception is thrown.

Leave a Comment