How to use PowerShell Break with the Label.


When the break statement is mentioned with the Label, PowerShell exits to the label instead of exiting the current loop.

Example

$i = 1
while ($i -lt 10) {
   Write-Output "i = $i"
   if($i -eq 5){
      Write-Output "Break statement executed"
      Break :mylable
   }
   $i++
}
Write-Output "Entering to another loop"
$j = 1
:mylable while($j -lt 3){
   Write-Output "j = $j"
   $j++
}

Output

i = 1
i = 2
i = 3
i = 4
i = 5
Break statement executed
Entering to another loop
j = 1
j = 2

As you can see in the above example when the value of 5 executed, the block containing label (mylable) is also executed and execution moves to another loop.

Updated on: 12-Mar-2020

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements