# How to use PowerShell break statement with the For loop?

PowerShellMicrosoft TechnologiesSoftware & Coding

#### Powershell for beginners

15 Lectures 3.5 hours

#### Learning Task Automation using Windows PowerShell

35 Lectures 2.5 hours

#### The Complete PowerShell 7 course: Beginner To Advanced

Most Popular

145 Lectures 12.5 hours

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"

## 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 =$jn"
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 =$jn"
}
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 07:25:17