PS> gci C:\
<<here it doesn't print the value of $? as 'true' after command executes>
PS> $?
true
但是,当我尝试使用自己的 powershell 函数重新创建此行为时,我得到:
PS> function test1 { write-host "hello"; return $true}
PS> test1
hello
true
PS> $?
true
是什么赋予了?为什么我不能隐藏管道中函数的返回值,而只将其写入$?多变的?
这是 PowerShell 中的众多自动变量之一,您可以通过运行以下命令查看完整列表:
get-help about_Automatic_Variables
的功能$?
是查看最后一个命令是否运行完成或遇到未捕获的错误。
例如
function Throw-WhenOdd($value){
if ($value % 2 -ne 0){
throw "OddNumber"
}
}
PS> Throw-WhenOdd 4
PS> $?
True
PS> Throw-WhenOdd 3
Exception:
Line |
3 | throw "OddNumber"
| ~~~~~~~~~~~~~~~~~
| OddNumber
PS>$?
False
PS> #Checking the value of `$?` resets the value
# so checking a second time returns true
PS> $?
true
总而言之,如果您有一个函数或 cmdlet 或其他任何东西并且它可以抛出异常,您可以使用$?
看看它是否抛出。但是,您必须使用 Throw 而不是 Write-Error,并且输出在您第一次检查时被消耗$?
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)