所以我正在使用PowerShell,并在下面的代码中遇到了一些令人惊讶的结果
function returns_true(){
return $true
}
function returns_false(){
return $false
}
if (returns_true -eq $true){
Write-Host "I return true"
}
if (returns_false -eq $false){
Write-Host "I return false"
}
$myval = returns_false
Write-Host $myval
运行它给我以下输出
I return true
False
我原以为这会回来
I return true
I return false
False
要不就
False
有人可以解释这里发生了什么。当我返回-eq $true
和-eq $false
时,PowerAhell在引擎盖下做什么让我能够评估$true
,而不是$false
?
这里实际发生的是解析器看到-eq $ true和-eq $ false作为传递给函数的参数。
要查看是这种情况,请将[CmdletBinding()] Param()添加到这样的函数中:
function returns_true(){
[CmdletBinding()]
Param()
return $true
}
更好地解释发生了什么:https://stackoverflow.com/a/49115149/9446818
括号帮助。你真正想要的是:
if ((returns_true) -eq $true){
和
if ((returns_false) -eq $false){