ASP.NET Weblogs

Welcome to ASP.NET Weblogs Sign in | Join | Help
in Search

The Technical Adventures of Adam Weigert

PowerShell: Try...Catch...Finally Comes To Life

So, PowerShell has some good error handling, but being so used to .NET, I really missed my Try...Catch...Finally statements. Especially when I needed to make sure a block of code always executed. Well, after some playing, I think I have the solution! I've tested this function in a few different ways. I hope this turns out to be as helpful to someone else as it is for me. Maybe Microsoft will add this functionality to the core of PowerShell.

function Try
{
    param
    (
        [ScriptBlock]$Command = $(throw "The parameter -Command is required."),
        [ScriptBlock]$Catch   = { throw $_ },
        [ScriptBlock]$Finally = {}
    )
   
    & {
        $local:ErrorActionPreference = "SilentlyContinue"
       
        trap
        {
            trap
            {
                & {
                    trap { throw $_ }
                    &$Finally
                }
               
                throw $_
            }
           
            $_ | & { &$Catch }
        }
       
        &$Command
    }

    & {
        trap { throw $_ }
        &$Finally
    }
}

# Example usage 

Try {
    echo " ::Do some work..."
    echo " ::Try divide by zero: $(0/0)"
} -Catch {
    echo "  ::Cannot handle the error (will rethrow): $_"
    #throw $_
} -Finally {
    echo " ::Cleanup resources..."
}

Published Oct 10 2007, 05:18 PM by adweigert
Filed under: ,

Comments

 

Cash Foley said:

Great stuff.  I can't figure out what the 'local' on ErrorActionPreference actually accomplishes.  Is the behavior actually different if you leave it off?

October 13, 2007 1:29 AM
 

adweigert said:

No, it isn't needed, I was just being explicit to show that this is only valid for the current scope.

It is just my personal standard when overriding a possible non-local variable.

October 13, 2007 10:24 AM
 

Trap [Exception] { “In PowerShell” } said:

Pingback from  Trap [Exception] { “In PowerShell” }

October 14, 2007 9:58 PM
 

Helge Klein said:

This looks great! I have been looking for this functionality for a long time.

Thanks for sharing this.

October 17, 2007 7:48 AM
 

Matt said:

Thanks for the function. I'm really excited to try this out. I've been playing around with this for the past 30 mins and am scratching my head more than I expected.

Could you by chance add additional example of calling the function (particularly examples of real-world catch blocks)? I think seeing more working examples would be very helpful.

Thanks again!

November 5, 2007 6:04 PM
 

Serge van den Oever [Macaw] said:

PowerShell has powerful exception handling, but it is badly documented and takes while to understand

November 22, 2007 10:53 AM
 

Try/Catch/Finally ?? PowerShell « PowerShell ?? ???????????? ?????????????? said:

Pingback from  Try/Catch/Finally ?? PowerShell « PowerShell ?? ???????????? ??????????????

April 23, 2008 1:19 AM
 

PowerShell и другие скрипты said:

PowerShell очень классный язык, но тем не менее очень молодой. И по этой причине в нём зачастую нет того чего хочется. Пока нет. Но так как он всё же очень классный - то чего нет можно дописать Вот к примеру если кому то не хватает привычной конструкции

April 23, 2008 1:22 AM
 

The Technical Adventures of Adam Weigert said:

So, I happened to come across a need for the using statement from C#. I basically didn't want to use

August 27, 2008 12:01 PM
 

Multi-Purpose PowerShell Using Function « Solutionizing .NET said:

Pingback from  Multi-Purpose PowerShell Using Function « Solutionizing .NET

September 21, 2008 6:42 PM
 

Chad Boyd said:

I ran across Adam Weigert's posting/script that provides a PoSh script that allows try/catch/finally

October 4, 2008 8:10 PM
 

PowerShell sur Technet et en français said:

La gestion des erreurs avec PowerShell V1 ne dispose pas des options évoluées de type try/catch/finally

December 14, 2008 6:30 AM
 

Using IDisposable Objects in PowerShell « Second Stanza said:

Pingback from  Using IDisposable Objects in PowerShell « Second Stanza

December 27, 2008 10:51 PM
 

Community Blogs said:

SharePoint Performance Optimizations for Large Programmatic User Profile Imports SharePoint Feature:

March 7, 2009 10:05 AM
 

Use PowerShell » Deep Dive: Error Handling – Error Types (part 1) said:

Pingback from  Use PowerShell » Deep Dive: Error Handling – Error Types (part 1)

July 21, 2009 8:03 AM
 

Try/catch in Powershell « Martin's Wonderful World of Exchange said:

Pingback from  Try/catch in Powershell «  Martin's Wonderful World of Exchange

August 27, 2009 3:18 AM
 

Try/catch in Powershell « Martin's Wonderful World of Exchange said:

Pingback from  Try/catch in Powershell «  Martin's Wonderful World of Exchange

August 27, 2009 3:20 AM
 

JC Blogs said:

In this blog I will show how to script syncing remote servers and add some useful exception handling

October 24, 2009 6:29 PM
 

PowerShell Tip: Adding Users Without an Email Address | SharePoint Blues said:

Pingback from  PowerShell Tip: Adding Users Without an Email Address | SharePoint Blues

June 2, 2010 12:59 PM
 

traffic travis discount said:

Pingback from  traffic travis discount

April 18, 2011 6:00 PM
 

Powershell try | Joininghandsca said:

Pingback from  Powershell try | Joininghandsca

December 9, 2011 10:00 PM