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.