Trap, which has been around since PowerShell v.1, is designed to catch errors and works like this:
Write-Host -foregroundcolor Yellow `
"Something terrible happened: $($_.Exception.Message)"; `
dir nonexistent: -ErrorAction Stop
"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:
dir nonexistent: -errorAction Stop
"Something strange occurred: $_"
ReTweet this Tip!
Sep 14 2009, 08:00 AM