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

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

问题描述

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



我阅读了关于自动变量的,并说:


$?包含上次操作的执行状态。如果最后一个操作成功,它包含TRUE。如果失败,则包含FALSE。



$ LastExitCode包含最近运行的基于Windows的程序。


$


$ b


我问,因为我推测如果且仅当$ LastExitCode为0时, $?为True,但我发现了一个令人惊讶的反例: $ LastExitCode = 0,但在PowerShell中$?= False。

$ LastExitCode 将stderr重定向到stdout会产生NativeCommandError code>是本机应用程序的返回代码。 $?只是返回 True False 最后一个命令(cmdlet或native)退出时没有错误或没有。



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

  PS> cmd / cexit 5
PS> $?
False
PS> cmd / cexit 0
PS> $?
True
C 也会算作失败;对于本地应用程序,它取决于它们设置的退出代码。


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.

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

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