Skip to content

The chain operators don't work with flow-control statements exit, return, and Throw #10967

Closed

Description

A common idiom (in the Bash world, which inspired PowerShell's && and || operators) is to conditionally exit a script when invocation of a command fails, along the lines of:

# Assume existence of /somepath and exit, if it doesn't exist.
ls /somepath || exit 1

Currently, neither exit nor return nor throw can be used on the RHS of && / ||

Steps to reproduce

{ Get-Item /nosuch || return  } | Should -Not -Throw
{ Get-Item / && return  } | Should -Not -Throw

Expected behavior

The tests should pass.

Actual behavior

The tests fail, because return is not recognized

Expected no exception to be thrown, but an exception 
"The term 'return' is not recognized as the name of a 
cmdlet, function, script file, or operable program. ..."...

Environment data

PowerShell Core 7.0.0-preview.6

Activity

  1. added
    Issue-Question
    on Nov 1, 2019
  2. added
    WG-Engine
    on Nov 1, 2019
  3. vexx32 commented on Nov 2, 2019

    @vexx32
    Collaborator
  4. rjmholt commented on Nov 2, 2019

    @rjmholt
    Collaborator

    Yes the PowerShell committee discussed this and it was decided against -- the RFC was updated to reflect that and it was taken out.

    Given the syntactic complexity of it, I think it was actually the right decision. There was a lot of inconsistency in the edge cases of this proposal. Instead, you can use a subexpression pretty easily: Get-Item ./doesntexist || $(exit 1). It's not beautiful, but it also doesn't set up weirdness like Get-Item ./doesntexist || throw "More things" && "other stuff" &. At that point it was starting to get very jagged between correct usage and bad. So simplicity won out.

  5. rjmholt commented on Nov 2, 2019

    @rjmholt
    Collaborator

    Also see:

    # Control flow statements
    @{ Statement = 'foreach ($v in 0,1,2) { testexe -returncode $v || $(break) }'; Output = @('0', '1') }
    @{ Statement = 'foreach ($v in 0,1,2) { testexe -returncode $v || $(continue); $v + 1 }'; Output = @('0', 1, '1', '2') }

  6. rjmholt commented on Nov 2, 2019

    @rjmholt
    Collaborator

    I did advocate fairly strongly for being able to use control flow statements in pipelines; I liked the idea and I think the concept is a nice one. Even though it didn't go in, I think it got a fair run.

    But syntactically it doesn't work because the big difference between PowerShell and bash is that in PowerShell statements contain pipelines, whereas the opposite it the case in bash. Trying to shoehorn certain kinds of statement where a pipeline fits just made the syntax really unhelpful, and you'd either have to make dodgy syntax breaking changes or implement very fiddly syntax rules to massage it in.

    The (badly named) subexpression syntax is designed for embedding a statement within a pipeline, so it offers this neatly.

  7. added
    Review - Committee
    on Nov 2, 2019
  8. mi-hol commented on Nov 3, 2019

    @mi-hol

    I wonder how the fact "syntactically it doesn't work because the big difference between PowerShell and bash" can we made clear to users. I had assumed that this new feature would basically work the same in PowerShell as in bash, hence many others will very likely start with the same assumption. At least this conclusion seems 'another nail in the coffin' for the goal 'pwsh is a replacement to bash' :(

  9. rjmholt commented on Nov 3, 2019

    @rjmholt
    Collaborator

    But it does work:

    { Get-Item /nosuch || $(return)  } | Should -Not -Throw
    { Get-Item / && $(return)  } | Should -Not -Throw
  10. vexx32 commented on Nov 3, 2019

    @vexx32
    Collaborator

    Rob Holt (@rjmholt) if that already works, I don't see it being especially sensible to mandate the awkward syntax.

  11. rjmholt commented on Nov 3, 2019

    @rjmholt
    Collaborator

    Prior to pipeline chains, the grammar was (I’m using a simplified shorthand here):

    statement:
     | ...
     | ‘return’ pipeline [‘&’]
     | pipeline [‘&’]
    
    pipeline:
     | pipeline ‘|’ command_expression
     | expression
    
    expression:
     | command_expression
     | ‘$(‘ statement ‘)’
    
    command_expression: ‘Get-Item /‘
    

    The current grammar just substitutes pipeline chains for pipelines, so that a pipeline is just a pipeline chain of length 1:

    statement:
     | ...
     | ’return’ pipeline_chain [‘&’]
     | pipeline_chain [‘&’]
    
    pipeline_chain:
     | pipeline_chain ‘&&’ pipeline
     | pipeline_chain ‘||’ pipeline
     | pipeline
    
    pipeline: <as above>
    

    If we allow control flow statements, then you might have this:

    pipeline_chain:
     | pipeline_chain ‘&&’ chain_element
     | pipeline_chain ‘||’ chain_element
     | chain_element
    
    chain_element:
     | ‘return’ pipeline_chain [‘&’]
     | pipeline
    

    That gives us back gi / && return, but now we have:

    • gi / && return “Hi” && return “what?”
    • gi / && return “Job” &
    • gi / && return “Job” & &
    • if (gi / && return “Hi”) { throw “Never thrown” }

    The biggest question is “what do I expect those to do” and if there’s no clear answer it’s not good syntax. So let’s fix it.

    Putting control flow statements only at the end of chains fixes nothing because they already enforce themselves as the ends of chains; once you use one, the chain to the right is subordinate to return because they have a pipeline_chain under them in the grammar.

    So let’s fix it instead by only allowing unchained pipelines under return. But now you can’t do return gi file && cat file.

    Ok we can fix that if we allow chains when return is the start of the statement but not when we’re in a chain. But now we have two kinds of return statement and pipelines aren’t just degenerate pipeline chains, they have all these caveats.

    And we still haven’t addressed how to deal with return 1 && 2 & vs 1 && return 2 &.

    And we also still haven’t addressed how to deal with control flow statements in places where only pipelines working as expressions used to be expected.

    In my original implementation that last was addressed by having two kinds of AST, so that return by itself wouldn’t just start working I’m an if or a while. But that meant tool implementors overriding VisitPipelineChainAst wouldn’t hit all the things that looked like &&/||, they also needed VisitStatementChain. Which was badly named since it didn’t apply to all statements. But then to make it apply to more statements we’d need to make even bigger changes in the syntax around job control and statement separation. And with each change we risk breaking compatibility with PS 5.1 and becoming more like Raku.

    So it’s a bit like the conversation Roy Batty has with Eldon Tyrell; every attempt to save the situation has some ugly consequence. To save that one tree we have to move the forest around it, and we’ve introduced more problems. A programming language’s grammar is a human interface that must be above all else consistent and composable. Inserting chaotic corner cases into the grammar makes it impossible to reason about or teach. And PowerShell needs to be defensible in 5 or 10 years time.

  12. vexx32 commented on Nov 4, 2019

    @vexx32
    Collaborator

    Right, but if it's already possible to make it "work" by using subexpression we should probably make an effort to formalize it in a way that is reasonably intuitive. Otherwise, the behaviour of such subexpressions will always be pretty ambiguous, unless you intend to completely disable keyword use in a pipeline chain.

  13. SteveL-MSFT commented on Nov 4, 2019

    @SteveL-MSFT
    Member

    An alternative is to make sure we include flow-control subexpressions in the examples for the documentation of this operator. Sub expressions is an existing concept and maybe users should use it more.

  14. mi-hol commented on Nov 4, 2019

    @mi-hol

    Steve Lee (@SteveL-MSFT), adding this to the documentation would be great! A search for the term gives 0 results currently!

    image

    or unrelated hits
    image

  15. SteveL-MSFT commented on Nov 6, 2019

    @SteveL-MSFT
    Member

    @PowerShell/powershell-committee reviewed this and we agree to that we will stay with what we agreed in the RFC which is that supporting flow-control statements complicates the implementation and using sub-expressions is the right way to use this. We should improve our documentation on sub-expressions if PowerShell users are not using them.

  16. 21 remaining items

  17. SeeminglyScience commented on Jul 26, 2020

    @SeeminglyScience
    Contributor

    I think it is a wrong thing to do. I would expect 0 && return 1 to fail even if there is some return.exe in the executable search path.

    Yeah I agree. Problem is that logic is very heavily relied on with the foreach alias pointing to ForEach-Object. That logic can't be changed without breaking a lot of folks.

  18. yecril71pl commented on Jul 26, 2020

    @yecril71pl
    Contributor

    So, returning to the problem at hand, if we allow && return then we should also allow && foreach, and then we rely on the fact that nobody would use Foreach-Object as the first pipline element, amirite? But what about nutjobs that would write 0 && foreach { $_ } -I 0 , and then they are broken?

  19. SeeminglyScience commented on Jul 26, 2020

    @SeeminglyScience
    Contributor

    So, returning to the problem at hand, if we allow && return then we should also allow && foreach, and then we rely on the fact that nobody would use Foreach-Object as the first pipline element, amirite?

    Believe it or not plenty of folks do. Especially if they are taking a ScriptBlock from an external source and want to emulate a process block. There are better ways to do it, but using ForEach-Object in the first pipeline slot is a pretty common way to do it.

    0 && foreach { $_ } -I 0 , and then they are broken?

    You got it. Not only would that no longer work, it would be a parse time error :/

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

  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.

  25. amis92 commented on Nov 23, 2023

    @amis92

    It's definitely not completed...

  26. 0009-0009-1013-986X commented on May 8, 2026

    @0009-0009-1013-986X
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

    Committee-ReviewedIssue-QuestionResolution-No ActivityWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions