PowerShell
There Is No
What to Use As an alternative of
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 { } whereasfor repeated actions. - Loop management:
breakandproceed(together with labeledbreak/proceedto focus on a selected loop orswap). - Conditional branching:
if/elseif/elseandswap(with highly effective matching options). - Early exit:
return(from features/scripts),throw(to sign errors), andattempt/catch/lastlyfor 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.
Printed by

