1

My team ran into a logic error when using the PowerShell -and operator. The operator produces an incorrect result when the left-hand side argument is a function and it is not wrapped in parenthesis:

function TrueFunction
{
  return $true
}

Write-Host "Zero:  " (TrueFunction)
Write-Host "One:   " (-not (TrueFunction))
Write-Host "Two:   " (!(TrueFunction))
Write-Host "Three: " ((-not (TrueFunction)))
Write-Host "Four:  " ((TrueFunction) -and (-not (TrueFunction)))
Write-Host "Five:  " (TrueFunction -and (-not (TrueFunction)))
Write-Host "Six:   " ($true -and (-not (TrueFunction)))

The expected output is:

Zero:   True
One:    False
Two:    False
Three:  False
Four:   False
Five:   False
Six:    False

while the actual output is:

Zero:   True
One:    False
Two:    False
Three:  False
Four:   False
Five:   True  // Wrong
Six:    False

Why is PowerShell producing an incorrect output for case five?

I reviewed this article on PowerShell logical operators and wrote the minimal program to reproduce the issue above.

mklement0
  • 382,024
  • 64
  • 607
  • 775
hpshelton
  • 11
  • 2
  • 2
    expected, `-and (-not (TrueFunction))` is seen as an argument of your function in example 5. should be `(TrueFunction) -and (-not (TrueFunction))` as shown in example 4 – Santiago Squarzon Apr 06 '23 at 21:22
  • 2
    Change your function body to `return @($true) + $args` and run example 5 again to see what I mean – Santiago Squarzon Apr 06 '23 at 21:28
  • 1
    To add to Santiago's comments, and to answer the question in your post's title: It isn't the `-and` operator, specifically, that requires enclosing function calls to be enclosed in `(...)` - it is a fundamental syntax requirement in order for _commands_ (which includes function calls) to be able to participate in _expressions_ - see the linked duplicate for details. – mklement0 Apr 06 '23 at 22:09

0 Answers0