Bash 的 && PowerShell 等效项是什么?和 ||运营商? [英] What are the PowerShell equivalents of Bash's && and || operators?
问题描述
在 Bash 中,我可以轻松地做类似的事情
In Bash I can easily do something like
command1 && command2 || command3
表示运行command1,如果command1成功运行command2,如果command1运行command3失败.
which means to run command1 and if command1 succeeds to run command2 and if command1 fails to run command3.
PowerShell 中的等价物是什么?
What's the equivalent in PowerShell?
推荐答案
Bash 必须做的是在传递给逻辑运算符时将命令的退出代码隐式转换为布尔值.PowerShell 不会这样做 - 但可以创建一个函数来包装命令并创建相同的行为:
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:
> function Get-ExitBoolean($cmd) { & $cmd | Out-Null; $? }
给定两个批处理文件:
#pass.cmd
exit
和
#fail.cmd
exit /b 200
...可以测试行为:
> if (Get-ExitBoolean .pass.cmd) { write pass } else { write fail }
pass
> if (Get-ExitBoolean .fail.cmd) { write pass } else { write fail }
fail
逻辑运算符的计算方式应与 Bash 中的相同.首先,设置一个别名:
The logical operators should be evaluated the same way as in Bash. First, set an alias:
> Set-Alias geb Get-ExitBoolean
测试:
> (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
这篇关于Bash 的 && PowerShell 等效项是什么?和 ||运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!