Share via


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.

Enjoy!

Sean
The EnergizedTech
Microsoft PFE

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

.EXAMPLE
# Get 4th record in PowerShell Error Array
$V=$Error[3]

#Retrieve Error Codes needed
Get-ErrorValue -ErrorRecord $v
#>
Function Get-ErrorValue
{
[cmdletbinding()]
param
(
$ErrorRecord=$Error[0]
)
[string]$Exception=$NULL
[string]$InnerException=$NULL

# Get Current Exception Value
If ($ErrorRecord.Exception -ne $NULL)
{
[String]$Exception=$ErrorRecord.exception.gettype().fullname
}

# Check if there is a more exacting Error code in Inner Exception
If ($ErrorRecord.exception.InnerException -ne $NULL)
{
[String]$InnerException=$ErrorRecord.Exception.InnerException.gettype().fullname
}

# If No InnerException or Exception has been identified
# Use GetBaseException Method to retrieve object
if ($Exception -eq '' -and $InnerException -eq '')
{
$Exception=$ErrorRecord.GetBaseException().gettype().Fullname
}

# Return values to user
[pscustomobject]@{'Exception'=$Exception;'InnerException'=$InnerException}
}