$之间的区别?和 PowerShell 中的 $LastExitCode

问题描述 投票:0回答:1

在 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.

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


我问这个问题是因为我认为当且仅当 $LastExitCode 为 0 时

$?
为 True,但我发现了一个令人惊讶的反例:PowerShell 中 $LastExitCode=0 但 $?=False。将 stderr 重定向到 stdout 会产生 NativeCommandError

windows powershell command-line
1个回答
123
投票

$LastExitCode
是本机应用程序的返回码。
$?
仅返回
True
False
,具体取决于最后一个命令(cmdlet 或本机)是否无错误退出。

对于 cmdlet 失败通常意味着异常,对于本机应用程序来说,它是非零退出代码:

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

使用 Ctrl+C 取消 cmdlet 也将被视为失败;对于本机应用程序,这取决于它们设置的退出代码。

© www.soinside.com 2019 - 2024. All rights reserved.