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?
On a general note:
trap
- liketry
/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:
$ErrorActionPreference = 'Stop'
in effect.Write-Error
aborts thetrap
script block too.The following simplified example illustrates this problem:
Note:
You don't need
Write-Error $_
in yourtrap
block in order to print the error at hand: Unless you usecontinue
to exit, it will print automatically, albeit after thetrap
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 thetrap
block from being aborted.