Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operator precedence in PowerShell

Tags:

powershell

Why does this expression return False instead of True ?

$true -or $false -and $false

-and should take precedence over -or, as confirmed by Microsoft Powershell documentation.

But it looks like the expression is evaluated as ($true -or $false) -and $false instead of $true -or ($false -and $false) !

Can someone explain to me what I'm missing here ?

like image 777
geoced Avatar asked Jan 24 '23 05:01

geoced


1 Answers

The linked documentation does not state that -and takes precedence over -or - instead, it states that -and and -or - perhaps surprisingly[1] - have equal precedence[2] in PowerShell.

Thus:

$true -or $false -and $false

is - due to implied left-associativity - evaluated as:

($true -or $false) -and $false  # -> $false

In other words: Use (...) to override this left-associativity on demand:

$true -or ($false -and $false)  # -> $true

[1] See GitHub issue #8512 for a discussion.

[2] The docs list -and -or -xor on the same line, implying that that all these operators have equal precedence.

like image 158
mklement0 Avatar answered Jan 30 '23 04:01

mklement0