2012-05-19 112 views
39

在PowerShell中,$?$LastExitCode之间有什么区别?

我读about automatic variables,它说:

$? Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

$LastExitCode Contains the exit code of the last Windows-based program that was run.

$?的定义,它并不能说明什么成功和失败的意思。


我问,因为我假定$?为真,当且仅当$ LastExitCode是0,但我发现一个令人惊讶的反例:$LastExitCode=0 but $?=False in PowerShell. Redirecting stderr to stdout gives NativeCommandError

回答

42

$LastExitCode是本地应用程序的返回码。 $?仅返回TrueFalse,具体取决于最后一条命令(cmdlet或本机)是否退出且没有错误。

对于小命令失败通常意味着一个例外,对于本机应用程序它是一个非零的退出代码:

PS> cmd /c "exit 5" 
PS> $? 
False 
PS> cmd /c "exit 0" 
PS> $? 
True 

取消与Ctrl键 + Ç也将计为失败小命令;对于本机应用程序,它取决于他们设置的退出代码。

+0

谢谢乔伊。我自己以为$?意味着非零退出代码,但我刚刚发现了一个令人惊讶的反例。见http://stackoverflow.com/questions/10666101/powershell-lastexitcode-0-but-false-redirecting-stderr-to-stdout-gives-nat –

+1

这是一个有趣的。我相信这是一个错误(因为它在不同的PowerShell主机之间行为不一致)。 – Joey

+0

和不同的cmdlet:@iex abcde @例如既不返回$?= False也不返回$ LastExitCode> 0 – majkinetor