2

Anyways in powershell i have the following script

function ReturnTrue()
{
    write-host "ReturnTrue executed!"
    return $true
}

if (ReturnTrue -and ReturnTrue -and ReturnTrue)
{
    write-host "ReturnTrue should have executed 3 times"
}

The expected output is to see "ReturnTrue executed!" printed 3 times but it's only printed once. Similar code in C# or Java would have executed ReturnTrue() 3 times. What's the deal?

1 Answer 1

6

Nice trap! Here is the code with its explanation in comments and the function also shows its arguments:

function ReturnTrue()
{
    write-host "ReturnTrue executed with $args!"
    return $true
}

# this invokes ReturnTrue once with arguments: -and ReturnTrue -and ReturnTrue
if (ReturnTrue -and ReturnTrue -and ReturnTrue)
{
    write-host "ReturnTrue should have executed 1 time"
}

# this invokes ReturnTrue 3 times
if ((ReturnTrue) -and (ReturnTrue) -and (ReturnTrue))
{
    write-host "ReturnTrue should have executed 3 times"
}

Output:

ReturnTrue executed with -and ReturnTrue -and ReturnTrue!
ReturnTrue should have executed 1 time
ReturnTrue executed with !
ReturnTrue executed with !
ReturnTrue executed with !
ReturnTrue should have executed 3 times
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.