TeamCity PowerShell scripts run with “- File” always return exit code zero

TeamCityAre you finding that your TeamCity Powershell scripts are always returning exit code zero (a success) no matter what happens? Even when an exception is thrown and you can see the error message in your build log?

I ran into this problem recently while moving some of my Powershell scripts into script files in source control. It turns out this is not an issue in TeamCity, but rather caused by a bug in Powershell itself. Never fear, there is a workaround!

The -File problem

The original Powershell bug details can be found on connect.microsoft.com. It was filed back in 2013, but doesn’t appear to be resolved yet. The crux of the issue is that if you run in -Command mode, errors in Powershell will return exit codes correctly when an exception occurs. When running in -File mode, this does not happen. This leads to your TeamCity Powershell build step ‘succeeding’ even though an error occurred.

The solution

To solve this, the script file being executed needs to do some explicit error handling in order to force the exit code. The below example script is something I used to force an exit when a script threw an exception:

try{
    #DO SOMETHING HERE
}
catch
{
    Write-Error $_
    ##teamcity[buildStatus status='FAILURE']
    [System.Environment]::Exit(1)
}

Another solution using ‘trap’ is also available on stackoverflow.com, but that syntax did not work for me in my scenario.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s