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 { } whilefor repeated actions. - Loop control:
breakandcontinue(including labeledbreak/continueto target a specific loop orswitch). - Conditional branching:
if/elseif/elseandswitch(with powerful matching features). - Early exit:
return(from functions/scripts),throw(to signal errors), andtry/catch/finallyfor 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



