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!
By day, I’m a systems admin for a medium size company in the Pacific Northwest.
By night, I’m a blogger, gamer, and all around general nerd.
If you found one of my articles useful, please consider supporting this site!
Monero: 48PxwMvbwoB2M86sHespLBKcSL9cWxrnJDmga9XshSqRP1joykRNpKkDGUz4ohhxD1bMH92poMyZWBBqkPmQ2bHpLP4EDnz
Bitcoin: bc1qc0fyze8x9lxp42x5p3zpry6f0lsr6l5pgq4jkh
Ethereum: 0xc613cBc79Ea4a84AE5538ec3321E214363305121