Trouble Executing Code Inside a PowerShell 'Trap' Block

41 Views Asked by At

I have a function that runs, and within this function, I've implemented a trap. However, it doesn't execute the code inside the trap. Instead, it writes an error message as expected, but it doesn't apply resource locks as intended. I can see that there are 7 LockObjects when it throws the error by printing the count, but is it possible to make it execute the code?

Here's the code:

# In case an error occurs, we will apply the locks back to the subscriptions
trap {
    Write-Error "$($LockObjects.count)"
    Write-Error $_
    foreach ($LockObject in $LockObjects) {
        Set-ResourceLock -SubscriptionId $LockObject.subscriptionId -Action Add -InputLocks $LockObject.LockObject
    }
}

Can anyone help me understand why the code within the trap block isn't being executed as expected, and how I can ensure it applies the resource locks correctly when an error occurs?

1

There are 1 best solutions below

2
On BEST ANSWER

On a general note:

  • trap - like try / catch - only operates on terminating errors, whereas non-terminating ones are far more typical. To convert the latter to terminating ones, use either -ErrorAction Stop or set $ErrorActionPreference = 'Stop' first. See this answer for background information.

You state that the trap block is executed in your case, yet only part of it is executed.

The likeliest explanation is:

  • You have $ErrorActionPreference = 'Stop' in effect.
  • As a result, your use of Write-Error aborts the trap script block too.

The following simplified example illustrates this problem:

function foo {
  $ErrorActionPreference = 'Stop'
  trap {
    Write-Error $_
    # !! THIS CODE IS NEVER REACHED.
    Write-Host 'After Write-Error.'
  }
  # Provoke an error
  1 / 0
}

foo

Note:

  • You don't need Write-Error $_ in your trap block in order to print the error at hand: Unless you use continue to exit, it will print automatically, albeit after the trap block has executed - see the conceptual about_Trap help topic.

  • If you want to use Write-Error for other reasons, add -ErrorAction Continue to prevent the trap block from being aborted.