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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10666035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:31:53  来源:igfitidea点击:

Difference between $? and $LastExitCode in PowerShell

windowspowershellcommand-line

提问by Colonel Panic

In PowerShell, what is the difference between $?and $LastExitCode?

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

I read about automatic variables, and it said:

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

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

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

In the definition of $?it doesn't explain what succeed and fail mean.

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



I ask because I presumed that $?is True if and only if $LastExitCode is 0, but I found a surprising counter-example: $LastExitCode=0 but $?=False in PowerShell. Redirecting stderr to stdout gives NativeCommandError.

我问是因为我认为$?当且仅当 $LastExitCode 为 0 时它才是 True,但我发现了一个令人惊讶的反例:$LastExitCode=0 但 $?=False 在 PowerShell 中。将 stderr 重定向到 stdout 会给出 NativeCommandError

回答by Joey

$LastExitCodeis the return code of native applications. $?just returns Trueor Falsedepending on whether the last command (cmdlet or native) exited without error or not.

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

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

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

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

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

使用Ctrl+取消 cmdletC也算作失败;对于本机应用程序,这取决于它们设置的退出代码。