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
...可以测试该行为:
...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
应该以与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屋!