Trap and Try/Catch

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

Trap, which has been around since PowerShell v.1, is designed to catch errors and works like this:

trap {
Write-Host -foregroundcolor Yellow `
"Something terrible happened: $($_.Exception.Message)"; `
continue
}

& {
dir nonexistent: -ErrorAction Stop
# any additional lines in this scope will be ignored
"Hello"
}

"I am back!"

Try/Catch is new in PowerShell v.2 and does not work as a general error handler in a given scope. Instead, you can use it to wrap statements you know could fail:

try {
dir nonexistent: -errorAction Stop
}
catch {
"Something strange occurred: $_"
}

Twitter This Tip! ReTweet this Tip!


Posted Sep 14 2009, 08:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.