My Powershell Script fails but the TeamCity build succeeds


It is a good practice to check in your build scripts into source control - that is, rather than embedding the script directly into the build server.  This is so you gain the advantages of version control and auditing, but also for the sake of reusability across builds.

One gotcha that I recently discovered in TeamCity was that when I executed a powershell script from a file, the build succeeded even when the script failed.  I was using a try..catch block, writing an error to the console and exiting with a 1.  In the build log, it would look like this:

[08:10:48][Step 2/5] 1
[08:10:48][Step 2/5] Process exited with code 0

The issue is because the powershell application succeeded in it's call and returns a 0.  The workaround is simple, instead of using Write-Error, use Write-Output in the catch block.  TeamCity will look for this and use the Exit value returned by the script, rather than what is returned from the application:

    #stuff happens here

    Write-Output -Exception $_.Exception
    Exit 1

More on this:

Mark Wojciechowicz

Labels: ,