How can I write to standard error from PowerShell, or trap errors such that:
Building on the idea in a previous answer, you can override the built-in Write-Error cmdlet temporarily with a custom function.
# Override the built-in cmdlet with a custom version
function Write-Error($message) {
[Console]::ForegroundColor = 'red'
[Console]::Error.WriteLine($message)
[Console]::ResetColor()
}
# Pretty-print "Something is wrong" on stderr (in red).
Write-Error "Something is wrong"
# Setting things back to normal
Remove-Item function:Write-Error
# Print the standard bloated Powershell errors
Write-Error "Back to normal errors"
With this you are utilizing the fact that Powershell Functions takes precedence over cmdlets.
https://technet.microsoft.com/en-us/library/hh848304.aspx
This is the most elegant approach I've been able to come up with to both show beautiful and concise error messages, as well as letting TeamCity detect problems easily.