In a script, when a command-let or other executable statement errors out, is there a try/catch type of mechanism to recover from these errors? I haven't run across one in the documentation.
views:
10509answers:
5You use a Trap [exception-type] {}
block before the code you want to handle exceptions for.
This MSDN appears to be helpful, also: http://channel9.msdn.com/wiki/windowspowershellquickstart
Here's someone (Adam Weigert) who implemented try/catch/finally using powershell. I use this in place of the built-in trap staement. Seems more natural.
http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx
I've written about this in my TechNet Magazine column (technetmagazine.com, if you're interested).
First, PowerShell v2 will have a standard Try...Catch, which is great.
The existing shell (v1) has support for trap {} constructs. These must be defined prior to the exception happening. Also, most cmdlets require an -EA "STOP" parameter in order for them to generate a trappable exception. Traps can be defined in any scope, and will "bubble" up until trapped or until they hit the global (shell) scope.
At the end of a trap, execute Continue to return to the next line of code in the same scope as the trap, or execute Break to leave the current scope and toss the exception up.