Powershell trap does not start sequentially

I cannot understand why I see this behavior in Powershell:

PS C:\> trap { "Got it!" } 1/0
Attempted to divide by zero.
At line:1 char:22
+ trap { "Got it!" } 1/0 <<<<

PS C:\> trap { "Got it!" } 1/$null
Got it!
Attempted to divide by zero.
At line:1 char:22
+ trap { "Got it!" } 1/$ <<<< null

Why does one expression cause a trap and the other does not?

+3
source share
1 answer

I would consider your first case as a parsing error. That is, the parser is trying to do a permanent folding (pre-calculate the value) and errors at this point, because it receives a division by a zero exception. Other syntax errors behave the same way, i.e. Do not start the trap:

trap { "Got it!" } 1/;
You must provide a value expression on the right-hand side of the '/' operator.

If you change the code to this:

$denom = 0
trap { "Got it!" } 1/$denom
Got it!
Attempted to divide by zero.

Then the trap is triggered, because the parser can no longer precompress the value.

+5
source

Source: https://habr.com/ru/post/1716914/


All Articles