Skip to content

&& and || pipeline chain operator should also check for $false #10917

Closed

Description

Support Question

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.

Activity

  1. added
    Issue-Question
    on Oct 27, 2019
  2. changed the title [-]&& and || pipeline chain operator and $false[/-] [+]&& and || pipeline chain operator should also check for $false[/+] on Oct 27, 2019
  3. vexx32 commented on Oct 27, 2019

    @vexx32
    Collaborator

    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.

    image

  4. KevinMarquette commented on Oct 28, 2019

    @KevinMarquette
    ContributorAuthor

    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 .

    Resolve-Path -Path testpath -ErrorAction SilentlyContinue || Write-Host "Second success"
    Second success
    

    Oddly enough, -ErrorAction Ignore also triggers the chain when I would expect it not to fail.

    Resolve-Path -Path testpath -ErrorAction Ignore || Write-Host "Second success"
    Second success
    

    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.

  5. SteveL-MSFT commented on Oct 28, 2019

    @SteveL-MSFT
    Member

    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.

  6. KevinMarquette commented on Oct 28, 2019

    @KevinMarquette
    ContributorAuthor

    Calling Write-Error will set $? to $false. But, if you call Write-Error from within a function, the function will set $? to $true.

    PS> function Test-Chain{
        Write-Error 'Failed'
    }
    
    PS> Test-Chain 
    Write-Error 'Failed': Failed
    PS> $?
    True
    

    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.

  7. vexx32 commented on Oct 28, 2019

    @vexx32
    Collaborator

    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.

  8. KevinMarquette commented on Oct 28, 2019

    @KevinMarquette
    ContributorAuthor

    I was thinking we could use it this way.

    PS> 
    function Test-Chain2{
        [cmdletbinding()]
        param()
        try{
            Write-Error 'Failed' -ErrorAction Stop
        }catch{
            $PSCmdlet.ThrowTerminatingError($PSitem)
        }
    }
    
    PS> Test-Chain2 || Write-Host "Second success"
    Test-Chain2: Failed
    Second success
    

    I'm looking for ways to make this work outside of native executables.

  9. KevinMarquette commented on Oct 28, 2019

    @KevinMarquette
    ContributorAuthor

    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
    
  10. vexx32 commented on Oct 28, 2019

    @vexx32
    Collaborator

    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?

  11. SteveL-MSFT commented on Oct 28, 2019

    @SteveL-MSFT
    Member
  12. KevinMarquette commented on Oct 28, 2019

    @KevinMarquette
    ContributorAuthor

    My ask would be that if $? was True, then perform the same evaluation we would do in if(...) or in the ternary operator.

  13. added
    WG-Language
    on Oct 28, 2019
  14. mklement0 commented on Oct 28, 2019

    @mklement0
    Contributor

    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.

  15. mklement0 commented on Oct 28, 2019

    @mklement0
    Contributor

    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 ;.

  16. 24 remaining items

  17. vexx32 commented on Nov 11, 2019

    @vexx32
    Collaborator

    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.

  18. Jaykul commented on Dec 5, 2019

    @Jaykul
    Contributor

    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?

    Test-Path $Path | Test-Pipeline || New-Item $Path
  19. Herr-Sepp commented on May 19, 2022

    @Herr-Sepp

    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.

  20. added
    Needs-Triage
    on May 19, 2022
  21. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    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.

  22. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    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.

  23. added
    Resolution-No Activity
    on Nov 16, 2023
  24. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-QuestionNeeds-TriageResolution-No ActivityWG-Language

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions