ASP.NET Weblogs

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

The Technical Adventures of Adam Weigert

October 2007 - Posts

  • 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..."
    }

More Posts