What are the PowerShell equivalents of Bash's && and || operators?&& Equivalent in PowershellPowershell: Bash && equivalentHow to tell PowerShell to wait for each command to end before starting the next?Can I get && to work in Powershell?conditional execution (&& and ||) in powershellHow to perform short-circuit evaluation in Windows PowerShell 4.0?ConvertTo-Html with null inputWhat is the Linux equivalent to DOS pause?How to iterate over arguments in a Bash scriptDoes Python have a ternary conditional operator?Setting Windows PowerShell environment variablesIn the shell, what does “ 2>&1 ” mean?In a Bash script, how can I exit the entire script if a certain condition occurs?Determine installed PowerShell versionTerminating a script in PowerShellPowerShell says “execution of scripts is disabled on this system.”How to stop a PowerShell script on the first error?
Will 700 more planes a day fly because of the Heathrow expansion?
In Stroustrup's example, what does this colon mean in `return 1 : 2`? It's not a label or ternary operator
Causes of bimodal distributions when bootstrapping a meta-analysis model
What if the end-user didn't have the required library?
Copy previous line to current line from text file
Are pressure-treated posts that have been submerged for a few days ruined?
What was the first sci-fi story to feature the plot "the humans were the monsters all along"?
Is there an idiom that support the idea that "inflation is bad"?
Is the set of non invertible matrices simply connected? What are their homotopy and homology groups?
Is there an official reason for not adding a post-credits scene?
What are the differences between credential stuffing and password spraying?
Why does this derived table improve performance?
How do inspiraling black holes get closer?
Building a list of products from the elements in another list
How to increase the size of the cursor in Lubuntu 19.04?
ZSPL language, anyone heard of it?
List of newcommands used
A factorization game
My advisor talks about me to his colleague
Homotopy limit over a diagram of nullhomotopic maps
Decoupling cap routing on a 4 layer PCB
How to safely wipe a USB flash drive
Should I decline this job offer that requires relocating to an area with high cost of living?
Should I dumb down my writing in a foreign country?
What are the PowerShell equivalents of Bash's && and || operators?
&& Equivalent in PowershellPowershell: Bash && equivalentHow to tell PowerShell to wait for each command to end before starting the next?Can I get && to work in Powershell?conditional execution (&& and ||) in powershellHow to perform short-circuit evaluation in Windows PowerShell 4.0?ConvertTo-Html with null inputWhat is the Linux equivalent to DOS pause?How to iterate over arguments in a Bash scriptDoes Python have a ternary conditional operator?Setting Windows PowerShell environment variablesIn the shell, what does “ 2>&1 ” mean?In a Bash script, how can I exit the entire script if a certain condition occurs?Determine installed PowerShell versionTerminating a script in PowerShellPowerShell says “execution of scripts is disabled on this system.”How to stop a PowerShell script on the first error?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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?
bash powershell language-comparisons
add a comment |
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?
bash powershell language-comparisons
stackoverflow.com/questions/1741490/… ?
– stej
Mar 10 '10 at 12:12
2
Stej, you did - stackoverflow.com/questions/2251622/…
– Keith Hill
Mar 10 '10 at 15:08
3
Interesting method to write your own over on superuser.
– ruffin
Nov 25 '14 at 15:24
Whoever is interested in Bash-style&&and||becoming a part of PowerShell: please vote for the feature here.
– mklement0
Jan 21 '17 at 19:12
add a comment |
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?
bash powershell language-comparisons
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?
bash powershell language-comparisons
bash powershell language-comparisons
edited Mar 22 at 23:18
dreftymac
16.4k2191154
16.4k2191154
asked Mar 10 '10 at 12:04
Andrew J. BrehmAndrew J. Brehm
1,89863562
1,89863562
stackoverflow.com/questions/1741490/… ?
– stej
Mar 10 '10 at 12:12
2
Stej, you did - stackoverflow.com/questions/2251622/…
– Keith Hill
Mar 10 '10 at 15:08
3
Interesting method to write your own over on superuser.
– ruffin
Nov 25 '14 at 15:24
Whoever is interested in Bash-style&&and||becoming a part of PowerShell: please vote for the feature here.
– mklement0
Jan 21 '17 at 19:12
add a comment |
stackoverflow.com/questions/1741490/… ?
– stej
Mar 10 '10 at 12:12
2
Stej, you did - stackoverflow.com/questions/2251622/…
– Keith Hill
Mar 10 '10 at 15:08
3
Interesting method to write your own over on superuser.
– ruffin
Nov 25 '14 at 15:24
Whoever is interested in Bash-style&&and||becoming a part of PowerShell: please vote for the feature here.
– mklement0
Jan 21 '17 at 19:12
stackoverflow.com/questions/1741490/… ?
– stej
Mar 10 '10 at 12:12
stackoverflow.com/questions/1741490/… ?
– stej
Mar 10 '10 at 12:12
2
2
Stej, you did - stackoverflow.com/questions/2251622/…
– Keith Hill
Mar 10 '10 at 15:08
Stej, you did - stackoverflow.com/questions/2251622/…
– Keith Hill
Mar 10 '10 at 15:08
3
3
Interesting method to write your own over on superuser.
– ruffin
Nov 25 '14 at 15:24
Interesting method to write your own over on superuser.
– ruffin
Nov 25 '14 at 15:24
Whoever is interested in Bash-style
&& and || becoming a part of PowerShell: please vote for the feature here.– mklement0
Jan 21 '17 at 19:12
Whoever is interested in Bash-style
&& and || becoming a part of PowerShell: please vote for the feature here.– mklement0
Jan 21 '17 at 19:12
add a comment |
3 Answers
3
active
oldest
votes
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) 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
10
So there is no simple built-in functionality for this?
– Andrew J. Brehm
Mar 10 '10 at 15:15
3
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. blogs.msdn.com/powershell/archive/2006/12/29/…
– James Kolpack
Mar 10 '10 at 15:51
1
Not sure the| Out-Nullis necessarily a good idea. Maybe pipe toWrite-Hostso we can still see the output?
– jpmc26
Aug 21 '14 at 14:40
1
@JamesKolpack: The only reason for the absence of both&&/||and the ternary conditional operator from the language is that they never made it to the top of the list - both have been acknowledged as potentially useful additions: see here for&&/||, and, with respect to the ternary operator, the very article you link to starts with "One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator."
– mklement0
Jan 24 '17 at 4:34
4
To be clear,Get-ExitCodeBoolean()is not a generic replacement for&&/||, because it suppresses regular output, preventing its capture in a variable / file / sending it through a pipeline. The beauty of Bash's&&/||control operators is that they don't interfere with the output streams and only act on the (invisible) exit codes - and that cannot (currently) be done in PowerShell. If you think it should, vote for it here.
– mklement0
Jan 24 '17 at 4:44
add a comment |
Many years after the question was first asked, let me summarize the state of affairs as of PowerShell v5.1:
Bash's /
cmd's&&and||control operators have NO PowerShell equivalents, and since you cannot define custom operators in PowerShell, there are no good workarounds:Use separate commands (on separate lines or separated with
;), and explicitly test the success status of each command via automatic variable$?, such as:command1 -arg1 -arg2; if ($?) command2 -arg1 # equivalent of &&command1 -arg1 -arg2; if (-not $?) command2 -arg1 # equivalent of ||See below for why PowerShell's
-andand-orare generally not a solution.
There was talk about adding them a while back, but it seemingly never made the top of the list.
- Now that PowerShell has gone open-source, an issue has been opened on GitHub.
- The tokens
&&and||are currently reserved for future use in PowerShell, so there's hope that the same syntax as in Bash can be implemented.
(As of PSv5.1, attempting something like1 && 1yields error messageThe token '&&' is not a valid statement separator in this version.)
Why PowerShell's -and and -or are no substitute for && and ||:
Bash's control operators && (short-circuiting logical AND) and || (short-circuiting logical OR) implicitly check the success status of commands by their exit codes, without interfering with their output streams; e.g.:
ls / nosuchfile && echo 'ok'
Whatever ls outputs -- both stdout output (the files in /) and stderr output (the error message from attempting to access non-existent file nosuchfile) -- is passed through, but && checks the (invisible) exit code of the ls command to decide if the echo command - the RHS of the && control operator - should be executed.
ls reports exit code 1 in this case, signaling failure -- because file nosuchfile doesn't exist -- so && decides that ls failed and, by applying short-circuiting, decides that the echo command need not be executed.
Note that it is exit code 0 that signals success in the world of cmd.exe and bash, whereas any nonzero exit code indicates failure.
In other words: Bash's && and || operate completely independently of the commands' output and only act on the success status of the commands.
PowerShell's -and and -or, by contrast, act only on the commands' standard (success) output, consume it and then output only the Boolean result of the operation; e.g.:
(Get-ChildItem , nosuchfile) -and 'ok'
The above:
uses and consumes the success (standard) output -- the listing of
-- and interprets it as a Boolean; a non-empty input collection is considered$truein a Boolean context, so if there's at least one entry, the expression evaluates to$true.- However, the error information resulting from nonexistent file
nosuchfileis passed through, because errors are sent to a separate stream.
- However, the error information resulting from nonexistent file
Given that
Get-ChildItem , nosuchfilereturns non-empty success output, the LHS evaluated to$true, so-andalso evaluates the RHS,'ok', but, again, consumes its output and interprets it as a Boolean, which, as a nonempty string, also evaluates to$true.Thus, the overall result of the
-andexpression is$true, which is (the only success) output.
The net effect is:
The success output from both sides of the
-andexpression is consumed during evaluation and therefore effectively hidden.The expression's only (success) output is its Boolean result, which is
$truein this case (which renders asTruein the terminal in English-language systems).
1
Huge hack, but I need an inline call and couldn't add functions. So I ended up with this:command1 ; $? -or (command3)
– Pedro Witzel
Apr 17 at 10:06
1
Interesting, @PedroWitzel; that would still output a Boolean, however, while suppressingcommand3's stdout output; to get closer to Bash's behavior, you'd need something likecommand1; $null = $? -or ($output = command3); $output, but that would print stderr output before stdout.
– mklement0
Apr 17 at 11:26
add a comment |
We can use try catch finally method instead of using && method in powershell.
try hostname catch echo err finally findstr bios
1
try/catchis pointless here, because it is only needed for terminating errors, which an external utility such ashostnamecannot trigger. Your code will unconditionally execute both commands.
– mklement0
Jan 21 '17 at 19:18
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2416662%2fwhat-are-the-powershell-equivalents-of-bashs-and-operators%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
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) 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
10
So there is no simple built-in functionality for this?
– Andrew J. Brehm
Mar 10 '10 at 15:15
3
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. blogs.msdn.com/powershell/archive/2006/12/29/…
– James Kolpack
Mar 10 '10 at 15:51
1
Not sure the| Out-Nullis necessarily a good idea. Maybe pipe toWrite-Hostso we can still see the output?
– jpmc26
Aug 21 '14 at 14:40
1
@JamesKolpack: The only reason for the absence of both&&/||and the ternary conditional operator from the language is that they never made it to the top of the list - both have been acknowledged as potentially useful additions: see here for&&/||, and, with respect to the ternary operator, the very article you link to starts with "One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator."
– mklement0
Jan 24 '17 at 4:34
4
To be clear,Get-ExitCodeBoolean()is not a generic replacement for&&/||, because it suppresses regular output, preventing its capture in a variable / file / sending it through a pipeline. The beauty of Bash's&&/||control operators is that they don't interfere with the output streams and only act on the (invisible) exit codes - and that cannot (currently) be done in PowerShell. If you think it should, vote for it here.
– mklement0
Jan 24 '17 at 4:44
add a comment |
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) 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
10
So there is no simple built-in functionality for this?
– Andrew J. Brehm
Mar 10 '10 at 15:15
3
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. blogs.msdn.com/powershell/archive/2006/12/29/…
– James Kolpack
Mar 10 '10 at 15:51
1
Not sure the| Out-Nullis necessarily a good idea. Maybe pipe toWrite-Hostso we can still see the output?
– jpmc26
Aug 21 '14 at 14:40
1
@JamesKolpack: The only reason for the absence of both&&/||and the ternary conditional operator from the language is that they never made it to the top of the list - both have been acknowledged as potentially useful additions: see here for&&/||, and, with respect to the ternary operator, the very article you link to starts with "One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator."
– mklement0
Jan 24 '17 at 4:34
4
To be clear,Get-ExitCodeBoolean()is not a generic replacement for&&/||, because it suppresses regular output, preventing its capture in a variable / file / sending it through a pipeline. The beauty of Bash's&&/||control operators is that they don't interfere with the output streams and only act on the (invisible) exit codes - and that cannot (currently) be done in PowerShell. If you think it should, vote for it here.
– mklement0
Jan 24 '17 at 4:44
add a comment |
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) 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
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) 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 Mar 10 '10 at 12:43
James KolpackJames Kolpack
8,49123755
8,49123755
10
So there is no simple built-in functionality for this?
– Andrew J. Brehm
Mar 10 '10 at 15:15
3
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. blogs.msdn.com/powershell/archive/2006/12/29/…
– James Kolpack
Mar 10 '10 at 15:51
1
Not sure the| Out-Nullis necessarily a good idea. Maybe pipe toWrite-Hostso we can still see the output?
– jpmc26
Aug 21 '14 at 14:40
1
@JamesKolpack: The only reason for the absence of both&&/||and the ternary conditional operator from the language is that they never made it to the top of the list - both have been acknowledged as potentially useful additions: see here for&&/||, and, with respect to the ternary operator, the very article you link to starts with "One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator."
– mklement0
Jan 24 '17 at 4:34
4
To be clear,Get-ExitCodeBoolean()is not a generic replacement for&&/||, because it suppresses regular output, preventing its capture in a variable / file / sending it through a pipeline. The beauty of Bash's&&/||control operators is that they don't interfere with the output streams and only act on the (invisible) exit codes - and that cannot (currently) be done in PowerShell. If you think it should, vote for it here.
– mklement0
Jan 24 '17 at 4:44
add a comment |
10
So there is no simple built-in functionality for this?
– Andrew J. Brehm
Mar 10 '10 at 15:15
3
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. blogs.msdn.com/powershell/archive/2006/12/29/…
– James Kolpack
Mar 10 '10 at 15:51
1
Not sure the| Out-Nullis necessarily a good idea. Maybe pipe toWrite-Hostso we can still see the output?
– jpmc26
Aug 21 '14 at 14:40
1
@JamesKolpack: The only reason for the absence of both&&/||and the ternary conditional operator from the language is that they never made it to the top of the list - both have been acknowledged as potentially useful additions: see here for&&/||, and, with respect to the ternary operator, the very article you link to starts with "One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator."
– mklement0
Jan 24 '17 at 4:34
4
To be clear,Get-ExitCodeBoolean()is not a generic replacement for&&/||, because it suppresses regular output, preventing its capture in a variable / file / sending it through a pipeline. The beauty of Bash's&&/||control operators is that they don't interfere with the output streams and only act on the (invisible) exit codes - and that cannot (currently) be done in PowerShell. If you think it should, vote for it here.
– mklement0
Jan 24 '17 at 4:44
10
10
So there is no simple built-in functionality for this?
– Andrew J. Brehm
Mar 10 '10 at 15:15
So there is no simple built-in functionality for this?
– Andrew J. Brehm
Mar 10 '10 at 15:15
3
3
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. blogs.msdn.com/powershell/archive/2006/12/29/…
– James Kolpack
Mar 10 '10 at 15:51
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. blogs.msdn.com/powershell/archive/2006/12/29/…
– James Kolpack
Mar 10 '10 at 15:51
1
1
Not sure the
| Out-Null is necessarily a good idea. Maybe pipe to Write-Host so we can still see the output?– jpmc26
Aug 21 '14 at 14:40
Not sure the
| Out-Null is necessarily a good idea. Maybe pipe to Write-Host so we can still see the output?– jpmc26
Aug 21 '14 at 14:40
1
1
@JamesKolpack: The only reason for the absence of both
&& / || and the ternary conditional operator from the language is that they never made it to the top of the list - both have been acknowledged as potentially useful additions: see here for && / ||, and, with respect to the ternary operator, the very article you link to starts with "One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator."– mklement0
Jan 24 '17 at 4:34
@JamesKolpack: The only reason for the absence of both
&& / || and the ternary conditional operator from the language is that they never made it to the top of the list - both have been acknowledged as potentially useful additions: see here for && / ||, and, with respect to the ternary operator, the very article you link to starts with "One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator."– mklement0
Jan 24 '17 at 4:34
4
4
To be clear,
Get-ExitCodeBoolean() is not a generic replacement for && / ||, because it suppresses regular output, preventing its capture in a variable / file / sending it through a pipeline. The beauty of Bash's && / || control operators is that they don't interfere with the output streams and only act on the (invisible) exit codes - and that cannot (currently) be done in PowerShell. If you think it should, vote for it here.– mklement0
Jan 24 '17 at 4:44
To be clear,
Get-ExitCodeBoolean() is not a generic replacement for && / ||, because it suppresses regular output, preventing its capture in a variable / file / sending it through a pipeline. The beauty of Bash's && / || control operators is that they don't interfere with the output streams and only act on the (invisible) exit codes - and that cannot (currently) be done in PowerShell. If you think it should, vote for it here.– mklement0
Jan 24 '17 at 4:44
add a comment |
Many years after the question was first asked, let me summarize the state of affairs as of PowerShell v5.1:
Bash's /
cmd's&&and||control operators have NO PowerShell equivalents, and since you cannot define custom operators in PowerShell, there are no good workarounds:Use separate commands (on separate lines or separated with
;), and explicitly test the success status of each command via automatic variable$?, such as:command1 -arg1 -arg2; if ($?) command2 -arg1 # equivalent of &&command1 -arg1 -arg2; if (-not $?) command2 -arg1 # equivalent of ||See below for why PowerShell's
-andand-orare generally not a solution.
There was talk about adding them a while back, but it seemingly never made the top of the list.
- Now that PowerShell has gone open-source, an issue has been opened on GitHub.
- The tokens
&&and||are currently reserved for future use in PowerShell, so there's hope that the same syntax as in Bash can be implemented.
(As of PSv5.1, attempting something like1 && 1yields error messageThe token '&&' is not a valid statement separator in this version.)
Why PowerShell's -and and -or are no substitute for && and ||:
Bash's control operators && (short-circuiting logical AND) and || (short-circuiting logical OR) implicitly check the success status of commands by their exit codes, without interfering with their output streams; e.g.:
ls / nosuchfile && echo 'ok'
Whatever ls outputs -- both stdout output (the files in /) and stderr output (the error message from attempting to access non-existent file nosuchfile) -- is passed through, but && checks the (invisible) exit code of the ls command to decide if the echo command - the RHS of the && control operator - should be executed.
ls reports exit code 1 in this case, signaling failure -- because file nosuchfile doesn't exist -- so && decides that ls failed and, by applying short-circuiting, decides that the echo command need not be executed.
Note that it is exit code 0 that signals success in the world of cmd.exe and bash, whereas any nonzero exit code indicates failure.
In other words: Bash's && and || operate completely independently of the commands' output and only act on the success status of the commands.
PowerShell's -and and -or, by contrast, act only on the commands' standard (success) output, consume it and then output only the Boolean result of the operation; e.g.:
(Get-ChildItem , nosuchfile) -and 'ok'
The above:
uses and consumes the success (standard) output -- the listing of
-- and interprets it as a Boolean; a non-empty input collection is considered$truein a Boolean context, so if there's at least one entry, the expression evaluates to$true.- However, the error information resulting from nonexistent file
nosuchfileis passed through, because errors are sent to a separate stream.
- However, the error information resulting from nonexistent file
Given that
Get-ChildItem , nosuchfilereturns non-empty success output, the LHS evaluated to$true, so-andalso evaluates the RHS,'ok', but, again, consumes its output and interprets it as a Boolean, which, as a nonempty string, also evaluates to$true.Thus, the overall result of the
-andexpression is$true, which is (the only success) output.
The net effect is:
The success output from both sides of the
-andexpression is consumed during evaluation and therefore effectively hidden.The expression's only (success) output is its Boolean result, which is
$truein this case (which renders asTruein the terminal in English-language systems).
1
Huge hack, but I need an inline call and couldn't add functions. So I ended up with this:command1 ; $? -or (command3)
– Pedro Witzel
Apr 17 at 10:06
1
Interesting, @PedroWitzel; that would still output a Boolean, however, while suppressingcommand3's stdout output; to get closer to Bash's behavior, you'd need something likecommand1; $null = $? -or ($output = command3); $output, but that would print stderr output before stdout.
– mklement0
Apr 17 at 11:26
add a comment |
Many years after the question was first asked, let me summarize the state of affairs as of PowerShell v5.1:
Bash's /
cmd's&&and||control operators have NO PowerShell equivalents, and since you cannot define custom operators in PowerShell, there are no good workarounds:Use separate commands (on separate lines or separated with
;), and explicitly test the success status of each command via automatic variable$?, such as:command1 -arg1 -arg2; if ($?) command2 -arg1 # equivalent of &&command1 -arg1 -arg2; if (-not $?) command2 -arg1 # equivalent of ||See below for why PowerShell's
-andand-orare generally not a solution.
There was talk about adding them a while back, but it seemingly never made the top of the list.
- Now that PowerShell has gone open-source, an issue has been opened on GitHub.
- The tokens
&&and||are currently reserved for future use in PowerShell, so there's hope that the same syntax as in Bash can be implemented.
(As of PSv5.1, attempting something like1 && 1yields error messageThe token '&&' is not a valid statement separator in this version.)
Why PowerShell's -and and -or are no substitute for && and ||:
Bash's control operators && (short-circuiting logical AND) and || (short-circuiting logical OR) implicitly check the success status of commands by their exit codes, without interfering with their output streams; e.g.:
ls / nosuchfile && echo 'ok'
Whatever ls outputs -- both stdout output (the files in /) and stderr output (the error message from attempting to access non-existent file nosuchfile) -- is passed through, but && checks the (invisible) exit code of the ls command to decide if the echo command - the RHS of the && control operator - should be executed.
ls reports exit code 1 in this case, signaling failure -- because file nosuchfile doesn't exist -- so && decides that ls failed and, by applying short-circuiting, decides that the echo command need not be executed.
Note that it is exit code 0 that signals success in the world of cmd.exe and bash, whereas any nonzero exit code indicates failure.
In other words: Bash's && and || operate completely independently of the commands' output and only act on the success status of the commands.
PowerShell's -and and -or, by contrast, act only on the commands' standard (success) output, consume it and then output only the Boolean result of the operation; e.g.:
(Get-ChildItem , nosuchfile) -and 'ok'
The above:
uses and consumes the success (standard) output -- the listing of
-- and interprets it as a Boolean; a non-empty input collection is considered$truein a Boolean context, so if there's at least one entry, the expression evaluates to$true.- However, the error information resulting from nonexistent file
nosuchfileis passed through, because errors are sent to a separate stream.
- However, the error information resulting from nonexistent file
Given that
Get-ChildItem , nosuchfilereturns non-empty success output, the LHS evaluated to$true, so-andalso evaluates the RHS,'ok', but, again, consumes its output and interprets it as a Boolean, which, as a nonempty string, also evaluates to$true.Thus, the overall result of the
-andexpression is$true, which is (the only success) output.
The net effect is:
The success output from both sides of the
-andexpression is consumed during evaluation and therefore effectively hidden.The expression's only (success) output is its Boolean result, which is
$truein this case (which renders asTruein the terminal in English-language systems).
1
Huge hack, but I need an inline call and couldn't add functions. So I ended up with this:command1 ; $? -or (command3)
– Pedro Witzel
Apr 17 at 10:06
1
Interesting, @PedroWitzel; that would still output a Boolean, however, while suppressingcommand3's stdout output; to get closer to Bash's behavior, you'd need something likecommand1; $null = $? -or ($output = command3); $output, but that would print stderr output before stdout.
– mklement0
Apr 17 at 11:26
add a comment |
Many years after the question was first asked, let me summarize the state of affairs as of PowerShell v5.1:
Bash's /
cmd's&&and||control operators have NO PowerShell equivalents, and since you cannot define custom operators in PowerShell, there are no good workarounds:Use separate commands (on separate lines or separated with
;), and explicitly test the success status of each command via automatic variable$?, such as:command1 -arg1 -arg2; if ($?) command2 -arg1 # equivalent of &&command1 -arg1 -arg2; if (-not $?) command2 -arg1 # equivalent of ||See below for why PowerShell's
-andand-orare generally not a solution.
There was talk about adding them a while back, but it seemingly never made the top of the list.
- Now that PowerShell has gone open-source, an issue has been opened on GitHub.
- The tokens
&&and||are currently reserved for future use in PowerShell, so there's hope that the same syntax as in Bash can be implemented.
(As of PSv5.1, attempting something like1 && 1yields error messageThe token '&&' is not a valid statement separator in this version.)
Why PowerShell's -and and -or are no substitute for && and ||:
Bash's control operators && (short-circuiting logical AND) and || (short-circuiting logical OR) implicitly check the success status of commands by their exit codes, without interfering with their output streams; e.g.:
ls / nosuchfile && echo 'ok'
Whatever ls outputs -- both stdout output (the files in /) and stderr output (the error message from attempting to access non-existent file nosuchfile) -- is passed through, but && checks the (invisible) exit code of the ls command to decide if the echo command - the RHS of the && control operator - should be executed.
ls reports exit code 1 in this case, signaling failure -- because file nosuchfile doesn't exist -- so && decides that ls failed and, by applying short-circuiting, decides that the echo command need not be executed.
Note that it is exit code 0 that signals success in the world of cmd.exe and bash, whereas any nonzero exit code indicates failure.
In other words: Bash's && and || operate completely independently of the commands' output and only act on the success status of the commands.
PowerShell's -and and -or, by contrast, act only on the commands' standard (success) output, consume it and then output only the Boolean result of the operation; e.g.:
(Get-ChildItem , nosuchfile) -and 'ok'
The above:
uses and consumes the success (standard) output -- the listing of
-- and interprets it as a Boolean; a non-empty input collection is considered$truein a Boolean context, so if there's at least one entry, the expression evaluates to$true.- However, the error information resulting from nonexistent file
nosuchfileis passed through, because errors are sent to a separate stream.
- However, the error information resulting from nonexistent file
Given that
Get-ChildItem , nosuchfilereturns non-empty success output, the LHS evaluated to$true, so-andalso evaluates the RHS,'ok', but, again, consumes its output and interprets it as a Boolean, which, as a nonempty string, also evaluates to$true.Thus, the overall result of the
-andexpression is$true, which is (the only success) output.
The net effect is:
The success output from both sides of the
-andexpression is consumed during evaluation and therefore effectively hidden.The expression's only (success) output is its Boolean result, which is
$truein this case (which renders asTruein the terminal in English-language systems).
Many years after the question was first asked, let me summarize the state of affairs as of PowerShell v5.1:
Bash's /
cmd's&&and||control operators have NO PowerShell equivalents, and since you cannot define custom operators in PowerShell, there are no good workarounds:Use separate commands (on separate lines or separated with
;), and explicitly test the success status of each command via automatic variable$?, such as:command1 -arg1 -arg2; if ($?) command2 -arg1 # equivalent of &&command1 -arg1 -arg2; if (-not $?) command2 -arg1 # equivalent of ||See below for why PowerShell's
-andand-orare generally not a solution.
There was talk about adding them a while back, but it seemingly never made the top of the list.
- Now that PowerShell has gone open-source, an issue has been opened on GitHub.
- The tokens
&&and||are currently reserved for future use in PowerShell, so there's hope that the same syntax as in Bash can be implemented.
(As of PSv5.1, attempting something like1 && 1yields error messageThe token '&&' is not a valid statement separator in this version.)
Why PowerShell's -and and -or are no substitute for && and ||:
Bash's control operators && (short-circuiting logical AND) and || (short-circuiting logical OR) implicitly check the success status of commands by their exit codes, without interfering with their output streams; e.g.:
ls / nosuchfile && echo 'ok'
Whatever ls outputs -- both stdout output (the files in /) and stderr output (the error message from attempting to access non-existent file nosuchfile) -- is passed through, but && checks the (invisible) exit code of the ls command to decide if the echo command - the RHS of the && control operator - should be executed.
ls reports exit code 1 in this case, signaling failure -- because file nosuchfile doesn't exist -- so && decides that ls failed and, by applying short-circuiting, decides that the echo command need not be executed.
Note that it is exit code 0 that signals success in the world of cmd.exe and bash, whereas any nonzero exit code indicates failure.
In other words: Bash's && and || operate completely independently of the commands' output and only act on the success status of the commands.
PowerShell's -and and -or, by contrast, act only on the commands' standard (success) output, consume it and then output only the Boolean result of the operation; e.g.:
(Get-ChildItem , nosuchfile) -and 'ok'
The above:
uses and consumes the success (standard) output -- the listing of
-- and interprets it as a Boolean; a non-empty input collection is considered$truein a Boolean context, so if there's at least one entry, the expression evaluates to$true.- However, the error information resulting from nonexistent file
nosuchfileis passed through, because errors are sent to a separate stream.
- However, the error information resulting from nonexistent file
Given that
Get-ChildItem , nosuchfilereturns non-empty success output, the LHS evaluated to$true, so-andalso evaluates the RHS,'ok', but, again, consumes its output and interprets it as a Boolean, which, as a nonempty string, also evaluates to$true.Thus, the overall result of the
-andexpression is$true, which is (the only success) output.
The net effect is:
The success output from both sides of the
-andexpression is consumed during evaluation and therefore effectively hidden.The expression's only (success) output is its Boolean result, which is
$truein this case (which renders asTruein the terminal in English-language systems).
edited May 23 '17 at 12:32
Community♦
11
11
answered Jan 23 '17 at 21:51
mklement0mklement0
142k23258294
142k23258294
1
Huge hack, but I need an inline call and couldn't add functions. So I ended up with this:command1 ; $? -or (command3)
– Pedro Witzel
Apr 17 at 10:06
1
Interesting, @PedroWitzel; that would still output a Boolean, however, while suppressingcommand3's stdout output; to get closer to Bash's behavior, you'd need something likecommand1; $null = $? -or ($output = command3); $output, but that would print stderr output before stdout.
– mklement0
Apr 17 at 11:26
add a comment |
1
Huge hack, but I need an inline call and couldn't add functions. So I ended up with this:command1 ; $? -or (command3)
– Pedro Witzel
Apr 17 at 10:06
1
Interesting, @PedroWitzel; that would still output a Boolean, however, while suppressingcommand3's stdout output; to get closer to Bash's behavior, you'd need something likecommand1; $null = $? -or ($output = command3); $output, but that would print stderr output before stdout.
– mklement0
Apr 17 at 11:26
1
1
Huge hack, but I need an inline call and couldn't add functions. So I ended up with this:
command1 ; $? -or (command3)– Pedro Witzel
Apr 17 at 10:06
Huge hack, but I need an inline call and couldn't add functions. So I ended up with this:
command1 ; $? -or (command3)– Pedro Witzel
Apr 17 at 10:06
1
1
Interesting, @PedroWitzel; that would still output a Boolean, however, while suppressing
command3's stdout output; to get closer to Bash's behavior, you'd need something like command1; $null = $? -or ($output = command3); $output, but that would print stderr output before stdout.– mklement0
Apr 17 at 11:26
Interesting, @PedroWitzel; that would still output a Boolean, however, while suppressing
command3's stdout output; to get closer to Bash's behavior, you'd need something like command1; $null = $? -or ($output = command3); $output, but that would print stderr output before stdout.– mklement0
Apr 17 at 11:26
add a comment |
We can use try catch finally method instead of using && method in powershell.
try hostname catch echo err finally findstr bios
1
try/catchis pointless here, because it is only needed for terminating errors, which an external utility such ashostnamecannot trigger. Your code will unconditionally execute both commands.
– mklement0
Jan 21 '17 at 19:18
add a comment |
We can use try catch finally method instead of using && method in powershell.
try hostname catch echo err finally findstr bios
1
try/catchis pointless here, because it is only needed for terminating errors, which an external utility such ashostnamecannot trigger. Your code will unconditionally execute both commands.
– mklement0
Jan 21 '17 at 19:18
add a comment |
We can use try catch finally method instead of using && method in powershell.
try hostname catch echo err finally findstr bios
We can use try catch finally method instead of using && method in powershell.
try hostname catch echo err finally findstr bios
edited Oct 11 '17 at 23:23
Arount
5,2821327
5,2821327
answered Jan 21 '17 at 16:32
CyberironCyberiron
51
51
1
try/catchis pointless here, because it is only needed for terminating errors, which an external utility such ashostnamecannot trigger. Your code will unconditionally execute both commands.
– mklement0
Jan 21 '17 at 19:18
add a comment |
1
try/catchis pointless here, because it is only needed for terminating errors, which an external utility such ashostnamecannot trigger. Your code will unconditionally execute both commands.
– mklement0
Jan 21 '17 at 19:18
1
1
try / catch is pointless here, because it is only needed for terminating errors, which an external utility such as hostname cannot trigger. Your code will unconditionally execute both commands.– mklement0
Jan 21 '17 at 19:18
try / catch is pointless here, because it is only needed for terminating errors, which an external utility such as hostname cannot trigger. Your code will unconditionally execute both commands.– mklement0
Jan 21 '17 at 19:18
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2416662%2fwhat-are-the-powershell-equivalents-of-bashs-and-operators%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
stackoverflow.com/questions/1741490/… ?
– stej
Mar 10 '10 at 12:12
2
Stej, you did - stackoverflow.com/questions/2251622/…
– Keith Hill
Mar 10 '10 at 15:08
3
Interesting method to write your own over on superuser.
– ruffin
Nov 25 '14 at 15:24
Whoever is interested in Bash-style
&&and||becoming a part of PowerShell: please vote for the feature here.– mklement0
Jan 21 '17 at 19:12