PowerShell logs even caught errors

An interesting PowerShell feature is that all errors are collected in an array called $error.

so for example if you throw an error you can echo $error and find it later:


However the error is also logged even if you catch it. Consider the following code snippet, which I’ve called errorcollectiontest.ps1


When running the script it outputs nothing, but when we check the errors array we find something interesting:


What does this matter?

Well if you have a system running PowerShell a convenient way to see if there were errors in the execution of a script is to check the $error array for any errors. However this array will also contain errors that were caught during the execution, which will introduce false-positives.

The PowerShell plugin for Hudson/Jenkins does exactly this, so if you want to use a PowerShell script that catches errors in Hudson/Jenkins the way to prevent false positive build results is to make the following change to the script:


This will remove the latest occurred error from the list, which just happens to be the error just caused since we entered the catch block.

<p>I’d like to mention <a href="http://johan.andersson.net/" target="_blank">Johan Andersson</a>, in this post, since without him it wouldn’t be written.</p>