Skip to content

Trap unhandled break statements #26587

Closed
Closed

Description

@iRon7

Summary of the new feature / enhancement

At first I saw the (labeled) break definition:

PowerShell does not limit how far labels can resume execution. The label can even pass control across script and function call boundaries.

as a convenient feature (INABIAF) to break out of the entire script (even from within a function) and keep the host alive.
But now I think it qualifies as a bug and should actually result in a (parser) error as it concerns a child function/script that potentially (accidentally) terminates the parent function/script.
Note that this also applies to break statements without labels, see e.g.: how to prevent external script from terminating your script with break statement)

A common use case where this might result is an cumbersome trouble shooting situation, is with testing where code misstakes (as label typos) should be captured rather than completely breaking the Pester script omitting any errors or results, see: pester/Pester#2669.

Proposed technical implementation details (optional)

Changing this behavior by default would result in a break change, but a kind of $UnhandledBreakUseErrorActionPreference variable (possibly with value as function-scope, script-scope and host-scope) might be helpful for testing and improving code quality. At a second thought, a preference variable is probably not the best solution as preference variables usually inherit their default setting from the parent script/function. but e.g. a TrapBreak function or trap break statement could be helpful to prevent (unintended) global breaks.
Wishful thinking:

# badscript.ps1
if((Get-Date).DayOfWeek -ne "Yesterday"){
    Write-Warning "Sorry, you can only run this script yesterday."
    break
}
function TrapBreakTest {
    trap break { 'unhandled break found.' }
    badscript.ps1
}

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Dec 8, 2025
  2. 237dmitry commented on Dec 8, 2025

    @237dmitry

    What's wrong with return, exit (and loop's break)?

  3. iRon7 commented on Dec 8, 2025

    @iRon7
    Author

    What's wrong with return, exit (and loop's break)?

    Nothing.
    What is wrong (imho), is that a break to a non-existing label doesn't produce an error but silently breaks all the parent scripts (including scripts as e.g. Pester).

  4. added
    WG-Engine
    on Dec 8, 2025
  5. changed the title [-]Unhandled `break` preference[/-] [+]Trap unhandled `break` statements[/+] on Dec 9, 2025
  6. jhoneill commented on Dec 9, 2025

    @jhoneill

    This should probably be extended to cover continue

    function test-2 {
    write-host "2-1"
    continue
    Write-host "2-2"
    }
    
    function test-1 {
    Write-host "1-1"
    test-2
    Write-host "1-2"
    }
    

    Few people expect this to exit a script which calls test-1

    # test.ps1
    write-host "boo"
    test-1
    write-host "moo"
    

    running test.ps1 outputs
    boo
    1-1
    2-1

  7. SeeminglyScience commented on Dec 14, 2025

    @SeeminglyScience
    Contributor

    More specifically it was likely implemented for ForEach-Object, at least that's how it's most likely to be used today.

    foreach ($a in $b) {
        $a | % { if ($_ -eq 2) { break } }
    }

    Also too many people use it today as a way to exit early. Even if incredibly ill-advised, it will technically work for a "controller style script". Making it a parse error would be a massive breaking change.

    An option at the host level to write an error when the REPL receives a break or continue exception could be a good idea, though every host that implements its own REPL would need to support the feature individually.

  8. SeeminglyScience commented on Jan 26, 2026

    @SeeminglyScience
    Contributor

    The Engine WG discussed this today, while we agree the scenario is hard to troubleshoot, we do not feel that adding this functionality to trap is ideal. We would suggest using the following code as a workaround in the rare case you need to make this determination.

    do {
        $breakOccurred = $true
        CommandWithBreak
        $breakOccurred = $false
    } while ($false)

    For troubleshooting you can also use Set-PSDebug -Trace 2 when attempting to diagnosis the issue.

  9. added
    Resolution-Declined
    WG-Reviewed
    and removed
    Needs-Triage
    on Jan 26, 2026
  10. iRon7 commented on Jan 27, 2026

    @iRon7
    Author

    Patrick Meinecke (@SeeminglyScience),

    We would suggest using the following code as a workaround in the rare case you need to make this determination.

    Thank you for your response but although the workaround works for a simple break (or continue) like:

    function CommandWithBreak { break }

    It doesn't work for a break (or continue) for a misspelled (non-existing) label, like:

    function CommandWithBreak {
      :misspell while ($true) {
        if ($true) { break mispell }
      }
    }
    function Test {
      do {
        $breakOccurred = $true
        CommandWithBreak
        $breakOccurred = $false
      } while ($false)
      Write-Host "CommandWithBreak: $([bool]$CommandWithBreak)"
    }

    Anyways, Set-PSDebug -Trace 2 certainly helps debugging this but is not something I would expect to be required while running Pester, see: pester/Pester#2669

  11. SeeminglyScience commented on Jan 27, 2026

    @SeeminglyScience
    Contributor

    True! It does not account for that, here's a better way:

    function DoWeirdBreak { break sdfsdf }
    
    $ps = $null
    try {
        $ps = [powershell]::Create('CurrentRunspace')
        $ps.AddScript{ DoWeirdBreak }.
            Invoke(
                @(),
                [System.Management.Automation.PSInvocationSettings]@{
                    ExposeFlowControlExceptions = $true
                })
    
    } catch [System.Management.Automation.BreakException] {
        'Break occurred with label: {0}' -f $_.Exception.Label
    } catch [System.Management.Automation.ContinueException] {
        'Continue occurred with label: {0}' -f $_.Exception.Label
    } finally {
        ($ps)?.Dispose()
    }
  12. microsoft-github-policy-service commented on Jan 28, 2026

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as declined and has not had any activity for 1 day. 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-EnhancementResolution-DeclinedWG-EngineWG-Reviewed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions