How do I get errors to propagate in the TeamCity PowerShell runner

There is an known bug in TeamCity that causes the behavior that the original poster noticed.

It is easy to work around, however.

At the end of your PowerShell script, add output indicating that the end of the script has been reached:

Echo "Packaging complete (end of script reached)"

Then, set up a new Build Failure Condition on your build to fail if the text you are echoing is NOT present in the output.


As doc'd in the friendly TeamCity manual:

Setting Error Output to Error and adding build failure condition

In case syntax errors and exceptions are present, PowerShell writes them to stderr. To make TeamCity fail the build, set Error Output option to Error and add a build failure condition that will fail the build on any error output.

The keys to making this work is to change two defaults:

  1. At the top level in the Build Failure Conditions, switch on an error message is logged by build runner:
  2. In the [PowerShell] Build Step, Show advanced options and set Error output: Error

In 9.1 the following works (I wouldn't be surprised if it works for earlier versions too):

  1. create a PowerShell Build Step with the default options
  2. change the dropdown to say Script: Source code
  3. Add a trap { Write-Error "Exception $_" ; exit 98 } at the top of the script
  4. (Optional but more correct IMO for the kind of scripting that's appropriate for within TeamCity build scripts)

    Show advanced options and switch on Options: Add -NoProfile argument

  5. (Optional, but for me this should be the default as it renders more clearly as suggested by @Jamal Mavadat)

    Show advanced options and switch on Error output: Error

    (ASIDE @JetBrains: if the label was "Format stderr output as" it would be less misleading)

This covers the following cases:

  1. Parse errors [bubble up as exceptions and stop execution immediately]
  2. Exceptions [thrown directly or indirectly in your PS code show and trigger an exit code for TC to stop the build]
  3. An explicit exit n in the script propagates out to the build (and fails it if non-zero)