7

We are using TeamCity Enterprise 8.0.5.

I have a TeamCity build step which runs a PowerShell (.ps1) script, which looks like this:

try
{
    # Break something
    $a = 1 / 0
}
catch
{
    Exit 1
}

Despite this, in the build log, the step succeeds and exits with code 0.

[10:02:18][Step 2/3] Process exited with code 0

I want the step to fail if there are any failures in the script. How can I make this happen?

tom redfern
  • 30,562
  • 14
  • 91
  • 126
  • Possible duplicate of [Why are my powershell exit codes always "0"?](http://stackoverflow.com/questions/15777492/why-are-my-powershell-exit-codes-always-0) – Michael Freidgeim Jan 18 '17 at 02:30

2 Answers2

9

I have just discovered this post:

PowerShell runner - script fails but the build succeeds - 'Process exited with code 0'

There is a bug in TeamCity which means that non-zero PowerShell return codes are not picked up.

The solution suggested is to create a build failure condition on detection of certain text output into the build log.

However, my solution involved something different.

In the catch block you only have to use the Write-Error cmdlet:

catch
{
    Write-Error -Exception $_.Exception
}

Then you must ensure that two things are set correctly in TeamCity:

Firstly, the build step Error Output should be set to error, and not warning:

Enter image description here

Secondly, in the build failure conditions screen, make sure an error message is logged by build runner is checked:

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tom redfern
  • 30,562
  • 14
  • 91
  • 126
  • 1
    This works, however in TeamCity 10.0.3 'Error output' referred above is called: 'Format stderr output as'. Also, any subsequent build steps needs to have value of 'Execute step' set to: 'Only if build status is successful' if they should be skipped – Emil G Jan 23 '17 at 10:26
-2

Suppose you are using psake and your goal is to fail your build if your build script fails. The script which imports the psake module and invokes the build script does not fail, so TeamCity takes it as a successful build.

Add this code into your first script to fail your build if the second script fails.

Import-Module .\psake\psake.psm1

Invoke-Psake .\build-steps.ps1 @args

if($psake.build_success -eq $false){
    Write-Host "There was an error running psake script"
    exit 1
}
Remove-Module psake

Do not remove the module before the if statement.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
wonderwall
  • 146
  • 1
  • 11