简而言之:
The Unix 实用程序的主要用途true
是将退出代码重置为0
在您故意想要忽略先前命令失败的情况下(通过nonzero退出代码)中类似 POSIX 的 shell,例如bash
,例如在条件语句中或使用 abort-on-unhandled-failures 选项set -e http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set有效。
两者都不true
也不是它的对应物,false
,产生任何output- 他们的唯一目的是设定一个退出代码.
PowerShell 本身不使用退出代码(尽管您可以为了外部呼叫者的利益而设置它们exit <n>
), and 它的条件做not对他们采取行动.
PowerShell 的自动的$?
多变的抽象地类似于$?
在类似 POSIX 的 shell 中,除了它报告Boolean,而 POSIX-like shell 报告退出代码;那是$?
含有0
在类似 POSIX 的 shell 中类似于$?
含有$true
在 PowerShell 中。
-
PowerShell 从不执行任何操作$?
隐含地,但您可以在 PowerShell 条件中使用它明确地,因此以下两个(为简单起见而设计)命令是等效的:
# POSIX-like shells:
# Event though the `ls` command fails `|| true` makes the overall
# command succeed.
if ls /nosuchfile || true; then echo success; fi
# PowerShell:
# `$?` would reflect `$false` after the failed `ls` command.
# `$null = $null` is a dummy command that resets `$?` to `$true`
# `$?` is then *output* for the `if` to test.
if ($(ls /nosuchfile; $null = $null; $?)) { 'success' }
虽然 PowerShell 有自动的$true
and $false
变量(概念上,常数),它们是Boolean values用于比较output(数据),not commands该集不可见的状态信息(退出代码)。
请继续阅读以了解背景信息。
类 POSIX shell 中的条件与 PowerShell 中的条件
In 类似 POSIX 的 shell例如bash
,条件操作于退出代码命令,即(执行后)状态信息,不是他们的output.
相比之下,电源外壳条件语句作用于命令或表达式output, i.e. data,不是状态信息。
简而言之:
两个炮弹都通过error输出(stderr)通过。
如果您希望 PowerShell 条件对命令(执行后)起作用status(成功与失败):
您可以使用自动的$?
多变的,其行为取决于手头的命令是 PowerShell 本机命令还是外部程序(例如 Unix 实用程序):
-
外部程序:如果程序的退出代码是0
, $?
反映$true
, 否则$false
-
PowerShell 本机命令(cmdlet、函数、脚本):$?
is $true
如果命令没有从根本上失败并且没有写入 PowerShell 的错误流(例如使用Write-Error
;注意stderr默认情况下,外部程序的输出是not写入 PowerShell 的错误流)。
- 注意
$?
因此不一定告诉您给定命令是否认为其整体执行成功;$?
being $false
只是告诉你some报告了错误。
- 但是,您可以将命令调用包装在
try { ... } catch { ... }
陈述,这对您有帮助区分非终止的 from 终止 errors(默认情况下只有后者触发catch
堵塞);
Use of $?
在 PowerShell 中并不常见,因为故障通常是用
-ErrorAction
常用参数 /$ErrorActionPreference
偏好变量和/或try { ... } catch { ... }
声明。
也就是说,这些方法不能用于外部程序, where testing $?
or $LASTEXITCODE
is a must来检测故障。
这个 GitHub 讨论 https://github.com/PowerShell/PowerShell/issues/9140 and 这个 RFC 草案 https://github.com/PowerShell/PowerShell-RFC/pull/88/files呼吁将外部程序与 PowerShell 的错误处理更好地集成。
有关 PowerShell 错误处理的全面概述,请参阅这个 GitHub 问题 https://github.com/PowerShell/PowerShell-Docs/issues/1583.