For some reason, modern error handling was left out of PowerShell Version 1.0. However, as both a tribute and a mockery to what is in and not in PowerShell, Adam Weigert posted the following PowerShell function in this post:
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..."}
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..."}
I did a bit of testing with nested error handling and I'm comfortable enough I'm going to start rolling it out.
Don't get me wrong, I LOVE PowerShell and for a version 1 product, it is amazingly functional and usable. But, I usually refer to the error handing as Trap Crap. It's not that it doesn't work... This function uses it and it works. But keep in mind, implementing your own Try Finally Catch using Trap Crap would look very similar to the Try implementation code! Can your read it? I can, but it takes too many brain cells and productive minutes to do so.
Compare it to the "Example usage". Hmmm... which do you want to use. It has a bit of awkwardness because of the "parameter" nature of the scriptblocks. Stick with the "} -Finally {" formatting. You'll have to do that or use continuation marks.
Until 2.0 comes out, this'll have to do.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.