Once more during the SharePointPro Magazine webinar last week one of the questions asked that we did not get a chance to respond to in the live session was about the PowerShell $error variable.

Although I cannot remember the specifics of the question, I recall that it was to do with the array nature of the $error variable and how we could interact with the array.

Let’s draw a quick example to explain the nature of the array.

From a fresh PowerShell session, I have entered “Gobbledeygook” and hit return. The result is as we would expect:

gobbledeygook

As “Gobbledeygook” is not a cmdlet, function, script file, or operable program we generate an error.

This is held in the $error variable which we can see by simply entering $error and hitting enter:

gobbledeygook2

If we now generate a second error (in this case I will call a non-existent method on $error):

gobbledeygook3
This is added to the $error array:

gobbledeygook4
Which we can now interact with in the normal way we can with any array in PowerShell:

gobbledeygook5

In the above example I have simply called the first item (index 0) from the array which as the $error variable is “last in first out” is the most recent error.

What’s the use of this?

With effective error trapping, we can maintain a pipeline of errors throughout script execution and use the array to check for specific errors (perhaps for reporting purposes) or to check for errors as we step through a script by testing against $error[0] which will always be the most recent error.

Armed with this knowledge (and coupled to making use of -errorvariable functionality available with many cmdlets) we no longer have to write scripts that call the $error.clear() method throughout to provide us a way to test against errors.

Neat and tidy, eh?

more to follow…