Fun with Errors

In the online PowerShell class I’ve been doing this week we’ve been discussing error handling. I explained that the built-in $error variable is an array that stores recent PowerShell exceptions.  Here’s a quick list of fun things you can do with an error object.

Want to see how many exceptions have occurred:

PS C:\> $error.count
96

Want to see the most recent exception:

PS C:\> $error[0]
Cannot convert value "named" to type "System.Int32". Error: "Input string was not in a correct format."At line:1 char:64
+ (($_.position -ne $()) -and ($_.position -ne "") -and ([int]$_.p <<<< osition -ne $()))

Did you know that there is more to this object?  Pipe $error to Get-Member to see for yourself. Or pipe it to Select-object as I’ve done here:

error

Many of the properties themselves are objects.

error2

You can really drill down into the object to find out what went wrong.

Finally, by default PowerShell only keeps track of the last 256 errors. Once $error has more than 256 entries, the older ones are removed to make room for newer errors. The $maximumErrorCount variable determines $error’s size which you can easily change.

PS C:\> $maximumErrorCount =512

So the next time an error occurs, don’t panic. Have some fun with it any maybe learn a little something as well.