Search code examples
windowspowershellwindows-server-2012-r2powershell-5.0

FuncOne() -and FuncTwo() not working


This is my code:

if (FuncOne($valOne) -and FuncTwo($valTwo)) {
    ...
}

When both of those functions evaluate to $false, the code within the if statement still executes. Why is that? This also does not work as expected:

if (FuncOne($valOne) -eq $true -and FuncTwo($valTwo) -eq $true) {
    ...
}

When written this way, it works as expected.

$a = FuncOne($valOne)
$b = FuncTwo($valTwo)

if($a -and $b) {
    ...
}

What's going on?


Solution

  • This is a syntax issue.

    The correct syntax for invoking functions in PowerShell is not:

    functionName($arg1[,$arg2,$arg3])
    

    but rather:

    functionName [-parameterName1] $arg1 [[-parameterName2] $arg2]
    

    Now, let's apply this to your if() sample expression:

    FuncOne $valOne -and FuncTwo $valTwo 
    

    You'll notice that explicit parameter names (-ParameterName) and operators (-and) are completely indistinguishable - there's no way for the parser to tell whether -and is supposed to be interpreted as a parameter name or an operator. Additionally, the string literal FuncTwo can just as well be interpreted as a parameter argument, which is exactly what happens.

    In order for the parser to know that you intend it to treat the expression as two separate expressions, force evaluation order with ():

    if ((FuncOne $valOne) -and (FuncTwo $valTwo)) {
        # They both returns a truthy value
    }