开发者

powershell function only executed once when called multiple times with -and in if condition

开发者 https://www.devze.com 2023-02-06 01:23 出处:网络
Anyways in powershell i have the following script function ReturnTrue() { write-host \"ReturnTrue executed!\"

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 th开发者_StackOverflow中文版e deal?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号