Understanding Trap Scope

by Dec 11, 2008

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'