PowerShell Error Catching

PowerShell error catching has been very frustrating for me. I try to do the right thing by putting code in a Try-Catch-Finally block, but continue to struggle with catching specific errors. I don’t know why the ‘thing’ I need to catch is not output with the error. I have to go through the error and ‘hunt’ for the thing to catch. Below is the basic syntax for a PowerShell Try-Catch-Finally block.

try {
    # Do something
} catch [something here to catch] {
    # Handle the error
} finally {
    # This section will always run
}

The sample below is similar to what you would typically see after an error is caught. Unfortunately, there is nothing in the output that you can use to ‘catch’.

What you end up having to do is use

$Error[0] | Format-List * -Force

This will show a longer output of the error, and more specifically, the ‘thing’ to ‘catch’. See the highlighted text below.

Now that there is a specific Exception to catch, we can add a new catch block to our Try-Catch-Finally block.

try {
    # Do something
} catch [System.Management.Automation.ParameterBindingException] {
    # Handle the specific error
} finally {
    # This section will always run
}

The best help I was able to find for this came from a Spiceworks post by Duffney, https://community.spiceworks.com/how_to/121063-using-try-catch-powershell-error-handling. It was by far the easiest method to discover the specific error to use in the catch block.

I am not quite sure why it is so hard to find the exception to use in the catch block or why it is just not part of the error output. I suppose for someone who codes in PowerShell everyday, this post will be laughable. I just wanted to make sure I recorded a post for future reference because I know for sure, I will struggle with this concept again.

Leave a Reply

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