powershell函数仅在使用-and in if条件多次调用时执行一次

bur*_*1ce 2 powershell

无论如何在powershell我有以下脚本

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

if (ReturnTrue -and ReturnTrue -and ReturnTrue)
{
    write-host "ReturnTrue should have executed 3 times"
}
Run Code Online (Sandbox Code Playgroud)

预期的输出是看"执行ReturnTrue!" 打印3次,但只打印一次.C#或Java中的类似代码将执行ReturnTrue()3次.这是怎么回事?

Rom*_*min 6

好陷阱!这是代码及其在注释中的解释,该函数还显示其参数:

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"
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)