Friday, December 4, 2026
HomePowershellOptions to the goto Assertion – SID-500.COM

Options to the goto Assertion – SID-500.COM


PowerShell

On this weblog publish, I’ll cowl alternate options to the goto assertion. Let’s dive in.

There Is No goto in PowerShell

PowerShell intentionally doesn’t implement a goto assertion. As an alternative, PowerShell supplies structured management movement that covers the identical sensible wants in a clearer and safer means.

What to Use As an alternative of goto

  • Loops: for, foreach, whereas, do { } whereas for repeated actions.
  • Loop management: break and proceed (together with labeled break/proceed to focus on a selected loop or swap).
  • Conditional branching: if/elseif/else and swap (with highly effective matching options).
  • Early exit: return (from features/scripts), throw (to sign errors), and attempt/catch/lastly for structured error dealing with.
  • Capabilities: Extract logic into features to keep away from leaping round—name the operate as a substitute of leaping to a label.

Examples

# Instance 1: Name Operator

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

# Instance 2: whereas loop with return assertion

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

# Instance 3: Proceed assertion (Label)

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


Hope this was useful.

Unknown's avatar

Printed by Patrick Gruenauer

Microsoft MVP on PowerShell & Microsoft 365, IT-Coach, IT-Guide, MCSE: Cloud Platform and Infrastructure, Cisco Licensed Academy Teacher.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments