PowerShell – Easily get Error Codes for Try Catch Finally

I was poking about with the whole Try Catch Finally segment in PowerShell.  Beautiful little scriptblock.


The stumbling block I kept hitting was getting the Error Code names.    How to get the default Exception has been documented online in various places.  However what I encountered was some Errors didn't match up with the examples provided.


Turns out in some cases you have a sort of "Main error" (your Exception) and then in SOME cases a second more exacting error (InnerException).  Then there is the 3rd really weird situation where NEITHER value is populated and you need to run a GetBaseException() method.

To make this easy on people (especially Us non Dev speaking IT Pros) I whipped together a little function in PowerShell to do the dirty work.


The EnergizedTech
Microsoft PFE

Return string values for Exception and InnerException from $Error records
This Cmdlet will return the Exception code and (if available) the Inner Exception values needed for a Try Catch Finally statement
# Return values from the most recent Error record

# Get 4th record in PowerShell Error Array

#Retrieve Error Codes needed
Get-ErrorValue -ErrorRecord $v
Function Get-ErrorValue

# Get Current Exception Value
If ($ErrorRecord.Exception -ne $NULL)

# Check if there is a more exacting Error code in Inner Exception
If ($ErrorRecord.exception.InnerException -ne $NULL)

# If No InnerException or Exception has been identified
# Use GetBaseException Method to retrieve object
if ($Exception -eq '' -and $InnerException -eq '')

# Return values to user

Comments (0)

Skip to main content