How to use PowerShell Break statement with the While Loop?

PowerShellMicrosoft TechnologiesSoftware & Coding

You can use the break statement with both the While loop and the Do-While loop.

To use the Break with a while loop, see the example below.

Example

$i = 1
While($i -ne 10){
   Write-Output $i
   if($i -eq 5){break}
   $i++
}

Output

1
2
3
4
5

In the above example, the loop terminates when the value of the variable $i reaches 5 because the Break statement is executed.

You can also use the break in the nested While loop, here we will take two examples of the nested loop. First when the break is placed outer loop and second when the break is placed in the inner loop.

Break statement in the Outer While loop −

Example

$i=1
$j=1
While($i -ne 10){
   while($j -ne 5){
      Write-Output "i = $i"
      Write-Output "j = $j`n"
      $j++
   }
   if($i -eq 5){Break}
   $i++
}

Output

i = 1
j = 1
i = 1
j = 2
i = 1
j = 3
i = 1
j = 4

The above example is of the outer loop break. When the value of $i becomes the 5, it terminates both the while loop.

Break statement in the Inner While loop −

Example

$i=1
$j=1
While($i -ne 5){
   while($j -ne 5){
      Write-Output "i = $i"
      Write-Output "j = $j`n"
      if($j -eq 3){Break}
      $j++
   }
   $i++
}

Output

i = 1
j = 1
i = 1
j = 2
i = 1
j = 3
i = 2
j = 3
i = 3
j = 3
i = 4
j = 3

When the value of $j becomes 3 in the above example, it terminates the child while loop and the execution move to the parent While loop and executes it.

Similarly, you can use the break statement with the Do-While loop as well as mentioned in the below example.

Break statement in the Do-While loop −

Example

$i = 1
do {
   Write-Output "i = $i"
   if($i -eq 3){Break}
   $i++
} while ($i -ne 5)

Output

i = 1
i = 2
i = 3
raja
Published on 12-Mar-2020 07:20:50
Advertisements