Powershell 中的“$?"是什么? [英] What is `$?` in Powershell?

查看:78
本文介绍了Powershell 中的“$?"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Powershell中$?是什么意思?

What is the meaning of $? in Powershell?

TechNet 回答 同义反复,没有解释什么是成功的' 或 '失败' 的意思.

TechNet answers in tautology, without explaining what 'succeed' or 'fail' mean.

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

$?
Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

我猜是 $?会简单地测试 $LastExitCode 是否为 0,但我发现了一个 反例 $?是 False 但 $LastExitCode 是 True.

I presumed $? would simply test whether $LastExitCode is 0, but I found a counter example where $? is False but $LastExitCode is True.

推荐答案

如果最后一条命令成功则返回true,否则返回false.

It returns true if the last command was successful, else false.

但是,有许多警告和不明显的行为(例如成功"的确切含义).我强烈建议阅读 这篇文章 以获得更全面的处理.

However, there are a number of caveats and non-obvious behaviour (e.g. what exactly is meant by "success"). I strongly recommend reading this article for a fuller treatment.

例如,考虑调用 Get-ChildItem.

For example, consider calling Get-ChildItem.

PS> Get-ChildItem 

PS> $? 
    True

$?调用 Get-ChildItem 成功时将返回 True.

$? will return True as the call to Get-ChildItem succeeded.

但是,如果您在不存在的目录上调用 Get-ChildItem,它将返回错误.

However, if you call Get-ChildItem on a directory which does not exist it will return an error.

PS> Get-ChildItem \Some\Directory\Which\Does\Not\Exist
    Get-ChildItem : Cannot find path 'C:\Some\Directory\Which\Does\Not\Exist' because it does not exist.

PS> $?
    False

$?将在此处返回 False,因为上一个命令未成功.

$? will return False here, as the previous command was not successful.

这篇关于Powershell 中的“$?"是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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