Monthly Archive

Categories

PowerShell for loop

PowerShell has a number of looping mechanisms – do-while; do-until; foreach; while and for loops. In this post I’ll show you how to use the PowerShell for loop.

A for loop iterates a predefined number 0f times. A basic for loop looks like this:

for ($i=0; $i -lt 10; $i++) {
$i
}

 

In the () you have 3 statements – they can be pipelines rather than simple assignments though most people just use assignments.

$i=0; - means set the counting variable $i to zero as the starting point

$i -lt 10; – means loop while the counting variable is less than 10

$i++ – means increment the counting variable by 1 after each loop

If you run the code you’ll see the numbers 0-9 displayed.

$i is traditionally used as the loop counting variable but it doesn’t have to be $i. It can be any arbitrary variable

for ($somevar=0; $somevar -lt 10; $somevar++) {
$somevar
}

 

The reason for using $i is traditional. It traces back to one of the early programming languages – Fortran – in which variables starting with i,j,k,l,m or n were integers by default. The variable i became the counter variable because of its position in the alphabet. The tradition has progressed down through programming languages since that day.

The loop count can be decremented

for ($i=0; $i -gt -10; $i--) {
$i
}

This loop will output 0 to –9

 

If you want to break out of a for loop use break

for ($i=0; $i -lt 10; $i++) {
if ($i -eq 5){break}
$i
}
Write-Host "I now equals $i"

which outputs

0
1
2
3
4
I now equals 5

 

Alternatively, to force the loop to skip further processing and move to the next iteration

for ($i=0; $i -lt 10; $i++) {
if ($i -eq 5){continue}
$i
}

which outputs 0-4 then 6-9

 

The for loop is a basic loop that’s best used when you want to iterate over a set of code a number of times.

You can use variables when assigning the start and endpoints

$x = 1
$y = 10
for ($i=$x; $i -lt $y; $i++) {
$i
}

 

Also, the loop counter doesn’t have to change by 1 each time

for ($i=0; $i -lt 10; $i+=2) {
$i
}

outputs 0,2,4,6,8

Comments are closed.