Powershell: Exception Analysis

Problem

I’v been having some trouble catching the correct Exception object in a try/catch-block.

Solution

Steps

Standard try/catch-block

try {
    #DoStuff
} catch [Exception] {
    #DoStuff
}

Create a test script to generate the exception again.

Use a standard try/catch-block to manipulate the exception object.
Read the exception object type from the “Exception” property and the exceptions code from the “ErrorCode” property

try {
    New-ADGroup -Name "Test" -Path "OU=Groups,DC=company,DC=com"
} catch {
    $_ | fl "Exception" -f
    $_.Exception | fl "ErrorCode" -f
}

Result:
Exception : Microsoft.ActiveDirectory.Management.ADException: The specified group already exists
ErrorCode : 1318

So the full name of an exception generated by Active Directory is Microsoft.ActiveDirectory.Management.ADException and the ErrorCode for the exception that gets thrown when the specified group already exists is 1318.

Result

This try/catch-block catches any Microsoft.ActiveDirectory.Management.ADException but will throw it up again if it is not the exception with ErrorCode 1318

try {
    New-ADGroup -Name "Test" -Path "OU=Groups,DC=company,DC=com"
} catch [Microsoft.ActiveDirectory.Management.ADException] {
    if($_.Exception.ErrorCode -eq 1318){
        #The specified group already exists
        #DoStuff
    } else {
        throw
    }
}
Advertisements

Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: