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

后端 未结 4 1362
一整个雨季
一整个雨季 2020-11-27 16:56

In Bash I can easily do something like

command1 && command2 || command3

which means to run command1 and if command1 succeeds to run

4条回答
  •  爱一瞬间的悲伤
    2020-11-27 17:45

    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; $? }
    

    ($? 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:

    > 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
    

提交回复
热议问题