views:

155

answers:

1

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?

+2  A: 

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
James Kolpack
So there is no simple built-in functionality for this?
Andrew J. Brehm
No, don't think so. I believe the designers did their best to avoid operator-hijacking usage like that. In fact, there's no ternary operator either. It is powerful enough, however, to provide the means to easily roll your own. http://blogs.msdn.com/powershell/archive/2006/12/29/dyi-ternary-operator.aspx
James Kolpack