PowerShell

PowerShell: Alternatives to the goto Statement

In this blog post, I will cover alternatives to the goto statement. Let’s dive in.

There Is No goto in PowerShell

PowerShell deliberately does not implement a goto statement. Instead, PowerShell provides structured control flow that covers the same practical needs in a clearer and safer way.

What to Use Instead of goto

  • Loops: for, foreach, while, do { } while for repeated actions.
  • Loop control: break and continue (including labeled break/continue to target a specific loop or switch).
  • Conditional branching: if/elseif/else and switch (with powerful matching features).
  • Early exit: return (from functions/scripts), throw (to signal errors), and try/catch/finally for structured error handling.
  • Functions: Extract logic into functions to avoid jumping around—call the function instead of jumping to a label.

Examples

# Example 1: Call Operator

$Start = {
    Write-Host "Im Start-Block"
    & $Weiter
}
$Weiter = {
    Write-Host "Im Weiter-Block"
    & $Ende
}
$Ende = {
    Write-Host "Im Ende-Block"
}
# Startpunkt
Clear-Host
& $Start

# Example 2: while loop with return statement

$BlockA = {
    Write-Host "Block A"
    return $BlockB
}
$BlockB = {
    Write-Host "Block B"
    return $BlockC
}
$BlockC = {
    Write-Host "Block C"
}
Clear-Host
$next = $BlockA
while ($next) {
    $next = & $next
}

# Example 3: Continue statement (Label)

:labelA for ($a = 0; $a -le 3; $a++) {
   
    if ($a -eq '1') 
    {
        continue labelB
    } 
    "a: $a"
    
:labelB for ($b = 1; $b -le 3; $b++) 
   
    { 
        "b: $b"
    }
        }


Hope this was helpful.

Categories: PowerShell

Tagged as: ,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.