Understanding Trap Scope

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

Traps are a great way of handling errors but you may want to control where PowerShell continues once an error occurs. There is a simple rule: a trap that uses the Continue keyword continues execution in the next line in the scope of the current trap. What does that mean?

If you only have one scope, PowerShell continues execution with the next statement following the error:

Trap { 'Something terrible happened.'; Continue}
'Hello'
1/$null
'World'

To create logical blocks, add scopes to your script, which can be functions or a basic script block. The next example will omit all remaining commands in the script block containing the error and PowerShell will continue with the next statement outside the script block:

Trap { 'Something terrible happened.'; Continue}
& {
'Hello'
1/$null
'World'
}
'Outside'

Posted Dec 11 2008, 08:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.