2012-05-19 78 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

相關問題