PowerShell exit code is always 0 in TeamCity 8 build step

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