Try/Catch/Finally

This post is part of the Second Wednesday Demo Session, Click here for more info about additional demo posts.

In PowerShell V2 we can use Try/Catch and Finally to control how scripts handle errors. Just as with the Trap statement, we can handle different types of errors.
Here’s a short function that shows how Try/Catch/Finally works.


function TryCatchError([scriptblock]$Command) {
  Try {
    & $Command
  }
  Catch [System.Management.Automation.PSInvalidCastException] {
    Write-Host "A PSInvalidCastException error occured" -ForegroundColor Red
  }
  Catch [System.DivideByZeroException] {
    Write-Host "A DivideByZeroException error occured" -ForegroundColor Red
  }
  Catch {
    Write-Host "Some other error occured" -ForegroundColor Red
  }
  Finally {
    "This part always executes, even if an error occurs."
  }
}

First, let’s generate an error of the type PSInvalidCastException.


PS > TryCatchError -Command { [int]1 + [string]"Hello" }

A PSInvalidCastException error occured
This part always executes, even if an error occurs.

Next we try to divide 1/$null.


PS > TryCatchError -Command { 1/$null }

A DivideByZeroException error occured
This part always executes, even if an error occurs.

If we try to create an instance of a .NET Object and specify a nonexisting class, the error is handled as expected.


PS > TryCatchError -Command { New-Object System.Blah }

Some other error occured
This part always executes, even if an error occurs.

Now let’s try Get-ChildItem and specify a nonexisting folder.


PS > TryCatchError -Command { Get-ChildItem C:\Blah }

Get-ChildItem : Cannot find path 'C:\Blah' because it does not exist.
At line:1 char:39
+ TryCatchError -Command { Get-ChildItem <<<<  C:\Blah }
    + CategoryInfo          : ObjectNotFound: (C:\Blah:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

This part always executes, even if an error occurs.

The Error is handled by the Get-ChildItem cmdlet rather than our Catch statement. Setting the ErrorAction parameter to Stop lets our Catch statement handle the error instead.


PS > TryCatchError -Command { Get-ChildItem C:\Blah -ErrorAction Stop }

Some other error occured
This part always executes, even if an error occurs.

Rating 3.00 out of 5
[?]

2 thoughts on “Try/Catch/Finally

  1. I have used try/catch before without any issues, so I am not sure what is going on here…

    Try{

    remove-item \\$name\c$\windows\temp\filename.exe}

    Catch {Write “Not able to access files on $name”}

    It always throws an error for the remove-item and it never catches it…. Am I missing something simple?

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Spam Protection by WP-SpamFree