How to use PowerShell break statement with the For loop?


To use the Break statement with the For loop, consider the below example.

Example

for($i=1; $i -le 10; $i++){
   Write-Host "i = $i"
   if($i -eq 5){break}
}

Output

i = 1
i = 2
i = 3
i = 4
i = 5

Here, when the value of $i reaches to 5, For loop gets terminated.

To use the Break with the nested For loop.

  • Inner For loop Break statement.

Example

for($i=1; $i -le 3; $i++){
   for($j=1; $j -le 5; $j++){
      Write-Host "i = $i"
      Write-Host "j = $j`n"
      if($j -eq 3){break}
   }
}

Output

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

Here, when the value of $j reaches 3, the only inner loop gets terminated but the outer loop execution still continues.

  • Outer For loop Break Statement.

Example

for($i=1; $i -le 3; $i++){
   for($j=1; $j -le 2; $j++){
      Write-Host "i = $i"
      Write-Host "j = $j`n"
   }
   if($i -eq 2){break}
}

Output

i = 1
j = 1
i = 1
j = 2
i = 2
j = 1
i = 2
j = 2

In the above example, when the value of $i reaches to 2 it breaks outer and inner loop both.

Updated on: 12-Mar-2020

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements