且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

if($?){}是否有Powershell模式

更新时间:2022-12-02 19:26:40

PowerShell [Core] 7.0 引入了类似Bash的& || 运算符称为 管道链操作符

PowerShell [Core] 7.0 introduced Bash-like && and || operators called pipeline-chain operators.

它们将回移植到 Windows PowerShell ,但是,后者通常不会看到任何新功能。

They will not be back-ported to Windows PowerShell, however, as the latter will generally see no new features.

简而言之,而不是

do-cmd-one; if ($?) { do-cmd-two }

您现在可以写

do-cmd-one && do-cmd-two

&&$ c> (AND)和 ||| (OR)隐式地对每个命令的暗示成功状态进行操作,这反映在自动布尔变量中$?

&& (AND) and || (OR) implicitly operate on each command's implied success status, as reflected in automatic Boolean variable $?.

这对于外部程序可能更有用,其退出代码明确表示 $? $ true (退出代码 0 )或 $ false (任何非零退出代码)。

This will likely be more useful with external programs, whose exit code unambiguously implies whether $? is $true (exit code 0) or $false (any nonzero exit code).

相比之下,对于PowerShell命令(cmdlet) $?仅反映该命令是否整体失败(发生了 statement-termination 错误)或是否报告了至少一个 non-terminated 错误;后者并不一定表示整体失败。

但是,有计划允许PowerShell命令直接设置 $? 作为有意的总体成功指示。

By contrast, for PowerShell commands (cmdlets) $? just reflects whether the command failed as a whole (a statement-terminating error occurred) or whether at least one non-terminating error was reported; the latter doesn't necessarily indicate overall failure.
However, there are plans to allow PowerShell commands to set $? directly, as a deliberate overall-success indicator.

还请注意,以下内容对& 和 || $ c不起作用$ c>

Also note that the following do not work with && and ||:


  • PowerShell的 Test-* cmdlet ,因为它们通过输出一个 Boolean 而不是通过设置 $?来表示测试结果;例如
    Test-Path $ somePath ||写警告文件丢失 不起作用。

  • PowerShell's Test-* cmdlets, because they signal the test result by outputting a Boolean rather than by setting $?; e.g.,
    Test-Path $somePath || Write-Warning "File missing" wouldn't work.

布尔值表达式,出于相同的原因;例如
$ files.Count -gt 0 ||写警告未找到文件 不起作用。

Boolean expressions, for the same reason; e.g.,
$files.Count -gt 0 || write-warning 'No files found' wouldn't work.

请参见此答案以获取背景信息以及此GitHub问题

See this answer for background information, and the discussion in this GitHub issue.

有一个语法警告:在撰写本文时,以下内容将起作用:

There's a syntax caveat: As of this writing, the following will not work:

do-cmd-one || exit 1 # !! Currently does NOT work

相反,您***打包退出 / 返回 / 抛出语句在 $(...) ,即所谓的子表达式运算符:

Instead, you're forced to wrap exit / return / throw statements in $(...), the so-called subexpression operator:

do-cmd-one || $(exit 1) # Note the need for $(...)

此GitHub问题讨论了这一尴尬要求的原因,这些原因植根于PowerShell语法的基础。

This GitHub issue discusses the reasons for this awkward requirement, which are rooted in the fundamentals of PowerShell's grammar.