views:

10509

answers:

5

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.

+5  A: 

Yes!

Have a read here:

http://huddledmasses.org/trap-exception-in-powershell/

Mark Ingram
+6  A: 

You use a Trap [exception-type] {} block before the code you want to handle exceptions for.

See http://huddledmasses.org/trap-exception-in-powershell/

Michael Burr
+2  A: 

This MSDN appears to be helpful, also: http://channel9.msdn.com/wiki/windowspowershellquickstart

warren
wow, maybe I should stop looking at the technet docs...
casademora
+1  A: 

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

Mike Shepard
+2  A: 

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.

Don Jones