Alex Rivera | Logout

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

Asked 2010-03-10T12:04:26.103
74

In Bash I can easily do something like

command1 && command2 || command3

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

What's the equivalent in PowerShell?

Edit
Report

1 Answer

12

What Bash must be doing is interpreting the integer exit code of the commands as true or false 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
answered 2010-03-10T12:43:31.727

Your Answer