How do I get errors to propagate in the TeamCity PowerShell runner
error-handling, powershell, teamcity
Solution
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:
- At the top level in the Build Failure Conditions, switch on an error message is logged by build runner:
- 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):
- create a PowerShell Build Step with the default options
- change the dropdown to say Script: Source code
- Add a `trap { Write-Error "Exception $_" ; exit 98 }` at the top of the script
(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
(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:
- Parse errors [bubble up as exceptions and stop execution immediately]
- Exceptions [`throw`n directly or indirectly in your PS code show and trigger an exit code for TC to stop the build]
- An explicit `exit n` in the script propagates out to the build (and fails it if non-zero)
Problem
I have a TeamCity 7 Build Configuration which is pretty much only an invocation of a `.ps1` script using various TeamCity Parameters. I was hoping that might be a simple matter of setting: Script File Script File %system.teamcity.build.workingDir%/Script.ps1 Script execution mode Execute .ps1 script with "-File" argument Script arguments %system.teamcity.build.workingDir% -OptionB %BuildConfigArgument% %BuildConfigArg2% And then I would expect: - if I mess up my arguments and the script won't start, the Build fails - if my Script.ps1 script throws, the Build fails - If the script `exit`s with a non-`0` Error Level I want the Build to Fail (maybe this is not idiomatic PS error management - should a .ps1 only report success by the absence of exceptions?) The question: It just doesn't work. How is it supposed to work? Is there something I'm doing drastically wrong that I can fix by choosing different options?