PowerShell 中 $? 和 $LastExitCode 的区别

在 PowerShell 中,$?$LastExitCode的区别是什么?

我读了 关于自动变量,上面说:

$? 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.

$?的定义中,它没有解释什么是成功和失败。


我这样问是因为我假设 $?是 True 当且仅当 $LastExitCode 是0,但我发现了一个令人惊讶的反例: $LastExitCode = 0 but $? = False in PowerShell 把 stderr 重定向到 stdout 会导致 NativeCommandError

101230 次浏览

$LastExitCode is the return code of native applications. $? just returns True or False depending on whether the last command (cmdlet or native) exited without error or not.

For cmdlets failure usually means an exception, for native applications it's a non-zero exit code:

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

Cancelling a cmdlet with Ctrl+C will also count as failure; for native applications it depends on what exit code they set.