Errors? What errors? Oh…..that $error.

We all hate it when your script throws an error. I mean they’re great when you’re writing the script. They help you figure out what’s wrong, but what if you need to keep a log of any errors after you’ve deployed the script?

Recently, I was putting a script together to a script to alert the IT department when a new guest account was created. So I wrapped everything up in a nice try {} catch {} block. I also needed to output any errors to an error log just in case something went wrong. (They always seems to eventually right?)

Well here’s an easy way to get them:

1
$error

So for example if I wanted to get the error output for Get-Item with -ErrorAction SilentlyContinue switch:

1
2
3
$error.Clear()
Get-Item -Path Idonotexist.txt -ErrorAction SilentlyContinue
$error

Or if I wanted to output the errors to a text file:

1
2
3
$error.Clear()
Get-Item -Path Idonotexist.txt -ErrorAction SilentlyContinue
$error >> C:\temp\error_log.txt

You’ll probably notice the $error.clear(). This is really handy to clear out the $error (array?).

Another fun trick with $error is you can select which error in the list you want to pick out. So the latest error will be $error[0]:

1
2
3
4
5
6
7
$error.Clear()
Get-Item -Path Idonotexist.txt -ErrorAction SilentlyContinue
Get-Item -Path Idonotexist323.txt -ErrorAction SilentlyContinue
Get-Item -Path Idonotexist123445.txt -ErrorAction SilentlyContinue
$error[0]
$error[1]
$error[2]

And you will get an output like this:

or if we want to make it a little cleaner we can add the .exception to $error

1
2
3
4
5
6
7
$error.Clear()
Get-Item -Path Idonotexist.txt -ErrorAction SilentlyContinue
Get-Item -Path Idonotexist323.txt -ErrorAction SilentlyContinue
Get-Item -Path Idonotexist123445.txt -ErrorAction SilentlyContinue
$error[0].exception
$error[1].exception
$error[2].exception

Much better!

Leave a Reply

Your email address will not be published. Required fields are marked *