You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
&& and || pipeline chain operator should also check for $false #10917
Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aNeeds-TriageThe issue is new and needs to be triaged by a work group.Resolution-No ActivityIssue has had no activity for 6 months or moreWG-Languageparser, language semantics
I was experimenting with the new && and || statement operators and they do not work like I would expect. A left hand side evaluation of $false is considered "succeed" in the chain operators.
Here is my specific use case where I ran into this issue:
Test-Path -Path $Path || return
I was exiting a function early when the file was missing. If the left side did not "succeed", I expected the right side to execute. That is not what happened.
Because of this unexpected behavior, I turned to the RFC0046-Chain-Operators document. I used the bash examples from the top of the document and translated them into PowerShell. The results did not match the inline description.
These two specific examples executed incorrectly (I replaced false with $false):
$false && echo 'Second success' # Executes only the left-hand command (false always "fails")
$false || echo 'Second success' # Executes both left-hand and right-hand commands
I have no background with bash so I was approaching this as a PowerShell user trying to do what felt intuitive. I expected the evaluation to work just like the if(...){...} statement when it came to "succeeded" or "not succeeded". This discrepancy will be a frequent source of confusion if it is left as implemented.
Reacted by Joel Bennett, Tatsunori Uchino, ExE Boss, Dan Thompson, Herr-Sepp, Doug Bailey, Brian and eabase
changed the title [-]&& and || pipeline chain operator and $false[/-][+]&& and || pipeline chain operator should also check for $false[/+]on Oct 27, 2019
The notes in the RFC section you mention indicate that in Bash, the result of false is always considered "failure", unlike in PowerShell where an expression can result in $true or $false while still being considered as executing successfully.
false&&echo'Second success'# Executes only the left-hand command (false always "fails")
That said, I agree that it feels a bit counterintuitive, especially as you also have to manually handle errors that occur within the expression if you want to hide the error from the user. I feel like if you're using an expression like <command> || something-else then you probably want that to BE your error handling, and not have to also take the additional effort to suppress / hide / handle the error after the expression completes.
I feel like we captured the technical bash implementation but not the spirit it of it.
The notes in the RFC section you mention indicate that in Bash, result of false is always considered "failure"
This statement leaves a lot open to interpretation.
in bash, false sets an exit code but PowerShell doesn't so false won't work like that in the chain operators
in bash, false is a failure so PowerShell should also treat $false as a failure in the chain operators
I do have to give it credit for giving us a good tool for working with native executable and a better way to handle the way they indicate errors. If that is all that is intended for it to ever do, we need to describe it as a native executable error handling feature. Instead of saying "succeeded" or not "succeeded", we should be clear in saying having errors/exit codes or does not have errors/exit codes.
But I am looking at this as someone trying to use it with PowerShell functions and it doesn't fit very well. My example is confusing because I am using Test-Path where $true is a "success" and $false is not "success". Because the implementation is tied to $?, we need a command that will give it a value. If I write my own test function, I can't set $? to 1 directly because it's readonly (and managed by the engine).
CmdLets
It was suggested that I use Resolve-Path instead because it gives an error. This will correctly trigger the chain operator. But I also get an error written to the console.
PS> Resolve-Path -Path $Path || Write-Host "Second success"
Resolve-Path: Cannot find path 'C:\temp\testpath' because it does not exist.
Second success
But we can control the error with -ErrorAction SilentlyContinue .
If we use -ErrorAction Stop, then we get an error but the chain is also stopped. If this was for error handling, don't we kind of need that to still execute?
Resolve-Path -Path testpath -ErrorAction Stop || Write-Host "Second success"
Cannot find path 'C:\temp\testpath' because it does not exist.
At line:1 char:1
I am getting some strange results with advanced functions using Write-Error. I'm going to experiment a bit more with that.
For the RFC, the @PowerShell/powershell-committee explicitly decided to only look at $?. This explains the behavior you're seeing. -ErrorAction Ignore doesn't put an error in $Error, but $? is still $false as that command failed. It's just that no error was produced. -ErrorAction Stop stops the script so the right side of || doesn't get a chance to execute. This would be the same if you throw without a catch.
This means that using Write-Error from a function is not sufficient to trigger the chain operators. I was able to get it to work if I used $PSCmdlet.ThrowTerminatingError($PSitem). So this will work with some functions but not others depending on how the internal error handling is managed.
Kevin Marquette (@KevinMarquette)ThrowTerminatingError() will terminate the entire expression, making || effectively useless. You can use $PSCmdlet.WriteError() to write a non-terminating error instead, which does correctly set $?
It's really silly that Write-Error doesn't do that from within a function, though; that's kind of what it's for in a very fundamental way, I think.
My last concern is that you need to use more errors to make use of these operators. But use of -ErrorAction Stop is common and would turn those into terminating errors.
PS>
function Test-Chain3 {
[cmdletbinding()]
param()
Resolve-Path -Path testpath || Write-Host "Second success"
}
PS> Test-Chain3
Resolve-Path:
Line |
4 | Resolve-Path -Path testpath || Write-Host "Second success"
| ^ Cannot find path 'C:\temp\testpath' because it does not exist.
Second success
PS> Test-Chain3 -ErrorAction Stop
Cannot find path 'C:\Users\kevma\testpath' because it does not exist.
At line:4 char:5
Given all the above, I have a fairly strong suspicion that with the present implementation of || we are vastly increasing the complexity of proper error handling in PS rather than simplifying it.
The present state of things here is not particularly great. Ideally, use of || should simplify error handling, not complicate it. I'll list out what I see as complications, along with possible resolutions.
Complication 1
|| lets errors bleed through, forcing us to silence or discard errors in addition to using || in many cases. As a result, use of || tends to complicate error handling, as we have to both apply an erroraction preference and take some other action.
Solution
Have || implicitly hide errors, while still populating $error as normal (a la -ErrorAction SilentlyContinue). This would allow us to do things like this: <command> || throw $error[0] (which effectively behaves akin to -ErrorAction Stop, but we could then apply this to an entire scriptblock, for example, which could terminate the parent command whilst still allowing the operations within the scriptblock to complete.
If || set $_ to the last error (or all errors?) it is handed during the execution of the left-hand command or expression, I think it could be rather useful to be able to do something like <command> || throw [AggregateException]::new($_.Exception) to collate all errors and exceptions into one thing to throw to the caller and handle there.
Complication 2
|| doesn't handle terminating errors, forcing us to use try/catch and making this an even more complicated tool to use; on a command line, <command> || <other-command> should probably not be a failing expression that just errors and does nothing else, by the very definition of || (at least in spirit).
Solution
Allowing || to also handle terminating errors would allow us to use it as a sort of inline try/catch, however, which vastly simplifies how we might handle such errors and whether we choose to rethrow them or not.
Complication 3
|| doesn't deal with $true/$false. I'm mostly stating this here as it's the main body of request for this issue. I think that we may want this to be the case. I'm not sure. With current behaviour we can do something like $var ? $result : $(throw) || <command> in lieu of implicit "$false is terrible" behaviour or perhaps a slightly simpler <command> | Assert-True || <command> sort of structure. That may be a bit too clunky for what we're looking for, though.
Solution
As Kevin has pointed out, we may want || to simply treat $false as an error, wherein it becomes a kind of soft-assert, which is treated as an error state and executes the fallback.
We do need to be careful introducing semantics around boolean conversions, I think, because several things can cast to $false in a boolean conversion, giving us a short list of things that would actually cause the error state to trigger here if they are handed to || as output:
$false itself
An empty array/collection: @()
The number zero: 0
An empty string: '' (possibly the most worrying, given there are probably at least a handful of native commands that don't output anything even when they do their job properly; this may need to be explicitly excluded so that it works with executables running with an /s switch for example).
An array with exactly one element that is any of the above.
Additional consideration here: should || be swallowing output from the left-hand side? Or would it conditionally swallow $false-y output? Or not at all?
As for Write-Error not setting $? in the caller's scope: that's a longstanding bug a fix for which has now gained urgency with && and || - see #3629
The workaround is to use $PSCmdlet.WriteError(), as Rain Sallow (/u/ta11ow) (@vexx32) mentioned, but, just like $PSCmdlet.ThrowTerminatingError(), it is only available in advanced functions / scripts.
As for -ErrorAction Ignore unexpectedly still resulting in $? reflecting $false: this is another known problem that Kirk Munro (@KirkMunro) reported a while ago - see #4613
Update: The correct behavior is debatable; if $? always resulted in $true with -ErrorAction Ignore, then combination with && / || is of limited use, because && would always and || never kick in - in which case you could just sequence commands with ;.
Quoting what I mentioned on Twitter with respect to that idea to keep the discussion more or less in one place:
Even if that works (which I think is infeasible as it would involve rewriting a good many core pwsh commands to include setting $?) you'd be diluting the purpose of $? so in reality this is not really different to having && or || respect true/false values from the output stream.
Also, we still need to fix $?; if this works:
Test-Path $path || New-Item $path
But this fails:
(Test-Path $path) || New-Item $Path
Then we still have a problem, imo. Technicalities or not, it will never make sense to users for a simple grouping to modify the result.
I don't think there's really a valid reason for keeping that behaviour from a UX standpoint. Since anything wrapped in a simple pair of ( ) (short of an actual parse error) sets $?=$true, that result is useless.
The problem is that we do not have any method of grouping statements that does not reset $?; to most folx, that task SHOULD fall to regular parentheses, as it does in every other language. Wrapping in parens should not change execution conditions.
it just so happens that tests are inherently quiet in Bash, due to being implemented as commands, not expressions.
Right, and in PowerShell tests are inherently Boolean and don't write errors or set $? to false. I mean, we all complain when someone makes a Test verb command that behaves differently, right? We want test commands to behave like Test-Path: return $true or $false without populating $error or $?
Which is why conditionally continuing operators that can't handle booleans don't make sense. Frankly, I'm not sure a command that sets $? when it gets falsish input is going to make things better:
Do we really think this is readable, or an expression we want to see?
How about new chain operators that take $true and $false into account?
I have stumbled over the problem of this issue so many times, but I also understand that && and || can't be changed easily.
(and maybe doesn't fit to powershell as default behavior either).
As a "simple" solution without breaking change I could imagine
&&&
and |||
as new chain operators that also consider boolean values.
This would be more readable than a new cmdlet that changes $? and has to be inserted into the pipeline as noted by Jaykul.
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commented on Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aNeeds-TriageThe issue is new and needs to be triaged by a work group.Resolution-No ActivityIssue has had no activity for 6 months or moreWG-Languageparser, language semantics
Activity
[-]&& and || pipeline chain operator and $false[/-][+]&& and || pipeline chain operator should also check for $false[/+]vexx32 commentedon Oct 27, 2019
The notes in the RFC section you mention indicate that in Bash, the result of
falseis always considered "failure", unlike in PowerShell where an expression can result in$trueor$falsewhile still being considered as executing successfully.That said, I agree that it feels a bit counterintuitive, especially as you also have to manually handle errors that occur within the expression if you want to hide the error from the user. I feel like if you're using an expression like
<command> || something-elsethen you probably want that to BE your error handling, and not have to also take the additional effort to suppress / hide / handle the error after the expression completes.KevinMarquette commentedon Oct 28, 2019
I feel like we captured the technical bash implementation but not the spirit it of it.
This statement leaves a lot open to interpretation.
I do have to give it credit for giving us a good tool for working with native executable and a better way to handle the way they indicate errors. If that is all that is intended for it to ever do, we need to describe it as a native executable error handling feature. Instead of saying "succeeded" or not "succeeded", we should be clear in saying having errors/exit codes or does not have errors/exit codes.
But I am looking at this as someone trying to use it with PowerShell functions and it doesn't fit very well. My example is confusing because I am using
Test-Pathwhere$trueis a "success" and$falseis not "success". Because the implementation is tied to$?, we need a command that will give it a value. If I write my own test function, I can't set$?to 1 directly because it's readonly (and managed by the engine).CmdLets
It was suggested that I use
Resolve-Pathinstead because it gives an error. This will correctly trigger the chain operator. But I also get an error written to the console.But we can control the error with
-ErrorAction SilentlyContinue.Oddly enough,
-ErrorAction Ignorealso triggers the chain when I would expect it not to fail.If we use
-ErrorAction Stop, then we get an error but the chain is also stopped. If this was for error handling, don't we kind of need that to still execute?I am getting some strange results with advanced functions using Write-Error. I'm going to experiment a bit more with that.
SteveL-MSFT commentedon Oct 28, 2019
For the RFC, the @PowerShell/powershell-committee explicitly decided to only look at $?. This explains the behavior you're seeing.
-ErrorAction Ignoredoesn't put an error in$Error, but$?is still$falseas that command failed. It's just that no error was produced.-ErrorAction Stopstops the script so the right side of||doesn't get a chance to execute. This would be the same if youthrowwithout acatch.KevinMarquette commentedon Oct 28, 2019
Calling
Write-Errorwill set$?to$false. But, if you callWrite-Errorfrom within a function, the function will set$?to$true.This means that using
Write-Errorfrom a function is not sufficient to trigger the chain operators. I was able to get it to work if I used$PSCmdlet.ThrowTerminatingError($PSitem). So this will work with some functions but not others depending on how the internal error handling is managed.vexx32 commentedon Oct 28, 2019
Kevin Marquette (@KevinMarquette)
ThrowTerminatingError()will terminate the entire expression, making||effectively useless. You can use$PSCmdlet.WriteError()to write a non-terminating error instead, which does correctly set$?It's really silly that
Write-Errordoesn't do that from within a function, though; that's kind of what it's for in a very fundamental way, I think.KevinMarquette commentedon Oct 28, 2019
I was thinking we could use it this way.
I'm looking for ways to make this work outside of native executables.
KevinMarquette commentedon Oct 28, 2019
My last concern is that you need to use more errors to make use of these operators. But use of
-ErrorAction Stopis common and would turn those into terminating errors.vexx32 commentedon Oct 28, 2019
Given all the above, I have a fairly strong suspicion that with the present implementation of
||we are vastly increasing the complexity of proper error handling in PS rather than simplifying it.The present state of things here is not particularly great. Ideally, use of
||should simplify error handling, not complicate it. I'll list out what I see as complications, along with possible resolutions.Complication 1
||lets errors bleed through, forcing us to silence or discard errors in addition to using||in many cases. As a result, use of||tends to complicate error handling, as we have to both apply an erroraction preference and take some other action.Solution
Have
||implicitly hide errors, while still populating$erroras normal (a la-ErrorAction SilentlyContinue). This would allow us to do things like this:<command> || throw $error[0](which effectively behaves akin to-ErrorAction Stop, but we could then apply this to an entire scriptblock, for example, which could terminate the parent command whilst still allowing the operations within the scriptblock to complete.If
||set$_to the last error (or all errors?) it is handed during the execution of the left-hand command or expression, I think it could be rather useful to be able to do something like<command> || throw [AggregateException]::new($_.Exception)to collate all errors and exceptions into one thing to throw to the caller and handle there.Complication 2
||doesn't handle terminating errors, forcing us to use try/catch and making this an even more complicated tool to use; on a command line,<command> || <other-command>should probably not be a failing expression that just errors and does nothing else, by the very definition of||(at least in spirit).Solution
Allowing
||to also handle terminating errors would allow us to use it as a sort of inline try/catch, however, which vastly simplifies how we might handle such errors and whether we choose to rethrow them or not.Complication 3
||doesn't deal with $true/$false. I'm mostly stating this here as it's the main body of request for this issue. I think that we may want this to be the case. I'm not sure. With current behaviour we can do something like$var ? $result : $(throw) || <command>in lieu of implicit "$falseis terrible" behaviour or perhaps a slightly simpler<command> | Assert-True || <command>sort of structure. That may be a bit too clunky for what we're looking for, though.Solution
As Kevin has pointed out, we may want
||to simply treat$falseas an error, wherein it becomes a kind of soft-assert, which is treated as an error state and executes the fallback.We do need to be careful introducing semantics around boolean conversions, I think, because several things can cast to
$falsein a boolean conversion, giving us a short list of things that would actually cause the error state to trigger here if they are handed to||as output:$falseitself@()0''(possibly the most worrying, given there are probably at least a handful of native commands that don't output anything even when they do their job properly; this may need to be explicitly excluded so that it works with executables running with an/sswitch for example).Additional consideration here: should
||be swallowing output from the left-hand side? Or would it conditionally swallow$false-y output? Or not at all?SteveL-MSFT commentedon Oct 28, 2019
cc Rob Holt (@rjmholt)
KevinMarquette commentedon Oct 28, 2019
My ask would be that if
$?was True, then perform the same evaluation we would do inif(...)or in the ternary operator.mklement0 commentedon Oct 28, 2019
As for
Write-Errornot setting$?in the caller's scope: that's a longstanding bug a fix for which has now gained urgency with&&and||- see #3629The workaround is to use
$PSCmdlet.WriteError(), as Rain Sallow (/u/ta11ow) (@vexx32) mentioned, but, just like$PSCmdlet.ThrowTerminatingError(), it is only available in advanced functions / scripts.mklement0 commentedon Oct 28, 2019
As for
-ErrorAction Ignoreunexpectedly still resulting in$?reflecting$false: this is another known problem that Kirk Munro (@KirkMunro) reported a while ago - see #4613Update: The correct behavior is debatable; if
$?always resulted in$truewith-ErrorAction Ignore, then combination with&&/||is of limited use, because&&would always and||never kick in - in which case you could just sequence commands with;.24 remaining items
vexx32 commentedon Nov 11, 2019
Quoting what I mentioned on Twitter with respect to that idea to keep the discussion more or less in one place:
Jaykul commentedon Dec 5, 2019
Right, and in PowerShell tests are inherently Boolean and don't write errors or set $? to false. I mean, we all complain when someone makes a
Testverb command that behaves differently, right? We want test commands to behave likeTest-Path: return$trueor$falsewithout populating$erroror$?Which is why conditionally continuing operators that can't handle booleans don't make sense. Frankly, I'm not sure a command that sets
$?when it gets falsish input is going to make things better:Do we really think this is readable, or an expression we want to see?
Herr-Sepp commentedon May 19, 2022
How about new chain operators that take $true and $false into account?
I have stumbled over the problem of this issue so many times, but I also understand that && and || can't be changed easily.
(and maybe doesn't fit to powershell as default behavior either).
As a "simple" solution without breaking change I could imagine
&&&
and
|||
as new chain operators that also consider boolean values.
This would be more readable than a new cmdlet that changes $? and has to be inserted into the pipeline as noted by Jaykul.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 23, 2023
This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.