什么是$?在Powershell中的别名?

Mar*_*agg 8 variables powershell alias

在我今天看到的一个脚本中是一行:

If ($?) {
#do some stuff
}
Run Code Online (Sandbox Code Playgroud)

我从未见过美元符号问号别名$?以前,我无法通过谷歌确定它是什么.

当我在PowerShell窗口中执行它时,它通常返回True,但偶尔会返回False.我的测试似乎表明,当它之前的代码在错误中执行时会返回False(并且在脚本的上下文中我看到它可能有意义)所以这可能是处理TRY的另一种方法.. CATCH场景.

例:

PS C:\Users\me> $?
True
PS C:\Users\me> $?
True
PS C:\Users\me> blah
blah : The term 'blah' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ blah
+ ~~~~
+ CategoryInfo          : ObjectNotFound: (blah:String) [],         CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\me> $?
False
PS C:\Users\me> $?
True
Run Code Online (Sandbox Code Playgroud)

任何人都可以验证我是否是这种情况或是否有其他目的?

小智 11

来自about_automatic_variables:

$?
包含上次操作的执行状态.如果上一次操作成功,则包含TRUE;如果失败,则包含FALSE.

Get-Help about_automatic_variables
Run Code Online (Sandbox Code Playgroud)