Does Windows Powershell have a Try/Catch or other error handling mechanism? Does Windows Powershell have a Try/Catch or other error handling mechanism? powershell powershell

Does Windows Powershell have a Try/Catch or other error handling mechanism?


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


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.


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