$之间的区别?和 $LastExitCode 在 PowerShell 中 [英] Difference between $? and $LastExitCode in PowerShell

查看:32
本文介绍了$之间的区别?和 $LastExitCode 在 PowerShell 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我阅读了关于自动变量,它说:<块引用>

<代码>$?包含上次操作的执行状态.如果上次操作成功,则包含 TRUE,如果失败则包含 FALSE.

$LastExitCode 包含最后运行的基于 Windows 的程序的退出代码.

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


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

解决方案

$LastExitCode 是本机应用程序的返回码.$? 仅返回 TrueFalse 取决于最后一个命令(cmdlet 或本机)是否正确退出.

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

PS>cmd/c "退出 5"PS>$?错误的PS>cmd/c "退出 0"PS>$?真的

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

In PowerShell, what is the difference between $? and $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.

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

这篇关于$之间的区别?和 $LastExitCode 在 PowerShell 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆