Bash 的 && 和 || 的 PowerShell 等效项是什么?运营商?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2416662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:46:43  来源:igfitidea点击:

What are the PowerShell equivalents of Bash's && and || operators?

bashpowershelllanguage-comparisons

提问by Andrew J. Brehm

In Bash I can easily do something like

在 Bash 中,我可以轻松地做类似的事情

command1 && command2 || command3

which means to run command1 and if command1 succeeds to run command2 and if command1 fails to run command3.

这意味着运行 command1,如果 command1 成功运行 command2,如果 command1 运行 command3 失败。

What's the equivalent in PowerShell?

PowerShell 中的等价物是什么?

采纳答案by James Kolpack

What Bash must be doing is implicitly casting the exit code of the commands to a Boolean when passed to the logical operators. PowerShell doesn't do this - but a function can be made to wrap the command and create the same behavior:

Bash 必须做的是在传递给逻辑运算符时将命令的退出代码隐式转换为布尔值。PowerShell 不会这样做 - 但可以创建一个函数来包装命令并创建相同的行为:

> function Get-ExitBoolean($cmd) { & $cmd | Out-Null; $? }

($? is a bool containing the success of the last exit code)

$? 是一个包含最后退出代码成功的布尔值

Given two batch files:

给定两个批处理文件:

#pass.cmd
exit

and

#fail.cmd
exit /b 200

...the behavior can be tested:

...行为可以被测试:

> if (Get-ExitBoolean .\pass.cmd) { write pass } else { write fail }
pass
> if (Get-ExitBoolean .\fail.cmd) { write pass } else { write fail }
fail

The logical operators should be evaluated the same way as in Bash. First, set an alias:

逻辑运算符的计算方式应与 Bash 中的相同。首先,设置别名:

> Set-Alias geb Get-ExitBoolean

Test:

测试:

> (geb .\pass.cmd) -and (geb .\fail.cmd)
False
> (geb .\fail.cmd) -and (geb .\pass.cmd)
False
> (geb .\pass.cmd) -and (geb .\pass.cmd)
True
> (geb .\pass.cmd) -or (geb .\fail.cmd)
True

回答by mklement0

Update: &&and ||are finally coming to PowerShell(Core), namely in v7; see the RFCand this answer.
At this point I'm unclear if the GA 7.0 version will expose these operators as an opt-in experimental featureonly at first.

更新&&||终于来到PowerShell的(核心),即在第7版; 请参阅RFC此答案
在这一点上,我不清楚 GA 7.0 版本是否会在开始时将这些运算符公开为可选的实验性功能



Many years after the question was first asked, let me summarize the state of affairs as of PowerShell v5.1:

在第一次提出这个问题多年后,让我总结一下 PowerShell v5.1 的情况

  • Bash's / cmd's &&and ||control operators have NO PowerShell equivalents, and since you cannot define custom operators in PowerShell, there are no good workarounds:

    • Use separate commands (on separate lines or separated with ;), and explicitly test the success status of each command via automatic variable $?, such as:
      command1 -arg1 -arg2; if ($?) { command2 -arg1 } # equivalent of &&
      command1 -arg1 -arg2; if (-not $?) { command2 -arg1 } # equivalent of ||

    • See below for why PowerShell's -andand -orare generally nota solution.

  • There was talk about adding thema while back, but it seemingly never made the top of the list.

    • Now that PowerShell has gone open-source, an issue has been opened on GitHub.
    • The tokens &&and ||are currently reserved for future use in PowerShell, so there's hope that the same syntax as in Bash can be implemented.
      (As of PSv5.1, attempting something like 1 && 1yields error message The token '&&' is not a valid statement separator in this version.)
  • bash的/cmd&&||控制运营商没有PowerShell的等价物,因为你不能在PowerShell中定义运营商定制,有没有很好的解决方法

    • 使用单独的命令(在单独的行或用 分隔;),并通过自动变量显式测试每个命令的成功状态$?,例如:
      command1 -arg1 -arg2; if ($?) { command2 -arg1 } # equivalent of &&
      command1 -arg1 -arg2; if (-not $?) { command2 -arg1 } # equivalent of ||

    • 请参阅下文,了解为什么 PowerShell 的-and-or通常不是解决方案。

  • 不久前有人谈论添加它们,但它似乎从未成为列表的顶部。

    • 现在 PowerShell 已经开源,GitHub 上也出现了一个问题
    • 令牌&&||当前保留供 PowerShell 将来使用,因此希望可以实现与 Bash 中相同的语法。
      (从 PSv5.1 开始,尝试类似的操作会1 && 1产生错误消息The token '&&' is not a valid statement separator in this version.


Why PowerShell's -andand -orare no substitute for &&and ||:

为什么 PowerShell 的-andand-or不能替代&&and ||

Bash's control operators &&(short-circuiting logical AND) and ||(short-circuiting logical OR) implicitly check the success status of commands by their exit codes, without interfering with their output streams; e.g.:

Bash的控制操作符&&(短路逻辑 AND)和||(短路逻辑 OR)通过它们的退出代码隐式地检查命令的成功状态,而不干扰它们的输出流;例如:

ls / nosuchfile && echo 'ok'

Whatever lsoutputs -- both stdout output (the files in /) and stderr output (the error message from attempting to access non-existent file nosuchfile) -- is passed through, but &&checks the (invisible) exit codeof the lscommand to decide if the echocommand - the RHS of the &&control operator - should be executed.

无论ls输出-标准输出输出(在文件中/)和stderr输出(从试图访问不存在的文件的错误信息nosuchfile) -是使其通过,但&&检查(不可见)退出代码的的ls命令,以决定是否echo指令-&&控制操作员的 RHS - 应该被执行。

lsreports exit code 1in this case, signaling failure-- because file nosuchfiledoesn't exist -- so &&decides that lsfailedand, by applying short-circuiting, decides that the echocommand need not be executed.
Note that it is exit code 0that signals success in the world of cmd.exeand bash, whereas any nonzeroexit code indicates failure.

ls1在这种情况下报告退出代码,发出信号失败- 因为文件nosuchfile不存在 - 所以&&决定ls失败,并通过应用短路,决定echo不需要执行命令。
请注意,这是退出代码0,在世界的信号成功cmd.exebash,而任何非零退出代码指示失败。

In other words: Bash's &&and ||operate completely independently of the commands' outputand only act on the success statusof the commands.

换句话说:Bash 的&&||完全独立于命令的输出运行,并且只对命令的成功状态起作用。



PowerShell's -andand -or, by contrast, act only on the commands' standard (success) output, consumeitand then output only the Boolean result of the operation; e.g.:

相比之下,PowerShell 的-andand-or仅作用于命令的标准(成功)输出使用,然后仅输出操作的布尔结果;例如:

(Get-ChildItem \, nosuchfile) -and 'ok'

The above:

以上:

  • uses and consumesthe success(standard) output -- the listing of \-- and interprets it as a Boolean; a non-empty input collection is considered $truein a Boolean context, so if there's at least one entry, the expression evaluates to $true.

    • However, the errorinformation resulting from nonexistent file nosuchfileispassed through, because errors are sent to a separate stream.
  • Given that Get-ChildItem \, nosuchfilereturns non-empty success output, the LHS evaluated to $true, so -andalso evaluates the RHS, 'ok', but, again, consumesits output and interprets it as a Boolean, which, as a nonempty string, also evaluates to $true.

  • Thus, the overall result of the -andexpression is $true, which is (the only success) output.

  • 用途和消耗成功(标准)输出-的上市\-和其解释为布尔; $true在布尔上下文中考虑非空输入集合,因此如果至少有一个条目,则表达式的计算结果为$true

    • 但是,由于文件不存在导致的错误信息nosuchfile传递,因为错误被发送到一个单独的流。
  • 鉴于Get-ChildItem \, nosuchfile返回非空成功输出,LHS 评估为$true,因此-and也评估 RHS,'ok',但是,再次消耗其输出并将其解释为布尔值,布尔值作为非空字符串,也评估为$true

  • 因此,-and表达式的总体结果是$true,这是(唯一成功的)输出

The net effectis:

净效应是:

  • The success outputfrom both sides of the -andexpression is consumedduring evaluation and therefore effectively hidden.

  • The expression's only (success) output is its Boolean result, which is $truein this case (which renders as Truein the terminal in English-language systems).

  • 表达式两边的成功输出在求值过程中-and消耗,因此被有效隐藏

  • 表达式的唯一(成功)输出是它的 Boolean result$true在这种情况下(True在英语语言系统的终端中呈现)。

回答by Cyberiron

We can use try catch finally method instead of using && method in powershell.

我们可以使用 try catch finally 方法而不是在 powershell 中使用 && 方法。

try {hostname} catch {echo err} finally {ipconfig /all | findstr bios}

回答by js2010

You can do something like this, where you hide the boolean output with [void], and only get the side effect. In this case, if $a or $b are null, then $c gets assigned to $result. An assignment can be an expression.

你可以做这样的事情,你用 [void] 隐藏布尔输出,只得到副作用。在这种情况下,如果 $a 或 $b 为空,则将 $c 分配给 $result。赋值可以是一个表达式。

$a = ''
$b = ''
$c = 'hi'

[void](
  ($result = $a) -or
  ($result = $b) -or
  ($result = $c))

$result

output

输出

hi