powershell function only executed once when called multiple times with -and in if condition
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
精彩评论