Using Traditional for
Loop
Use the traditional for
loop to print from 1
to 10
on the PowerShell console.
1 2 3 4 5 |
for ($i = 1; $i -le 10; $i++) { Write-Host "The Iteration Number is: $i" } |
1 2 3 4 5 6 7 8 9 10 11 12 |
The Iteration Number is: 1 The Iteration Number is: 2 The Iteration Number is: 3 The Iteration Number is: 4 The Iteration Number is: 5 The Iteration Number is: 6 The Iteration Number is: 7 The Iteration Number is: 8 The Iteration Number is: 9 The Iteration Number is: 10 |
In the above example, we used the traditional for
loop to iterate from 1
to 10
. The header of the for
loop consists of three parts separated by a semicolon (;
). The first part is the Initialization
placeholder, the second is called Condition
or Test Expression
, and the third is Repeat
. All three parts are enclosed in parentheses (()
) followed by the for
keyword. Let’s understand them below:
The Initialization
placeholder consists of one or multiple commands that run before the for
loop starts. It is used to define and initialize a variable with an initial value. For example, in the above code, the $i=1
expression is the initialization part where the i
variable is initially set to 1
. This variable is accountable for holding values from 1
to 10
(one at a time). Note that the variables are prefixed with $
in PowerShell.
The Condition
or Test Expression
placeholder returns a Boolean value (True
/False
) in each loop iteration. We can also have multiple conditions here. As per the above code snippet, the $i -le 10
is the Condition
, which determines if the value of $i
is less than or equal to 10
using the -le
operator. Note that the condition is evaluated in each iteration of the loop until it becomes False
. If this test expression returns True
, the body of the for
loop (enclosed within {}
) gets executed; otherwise, it does not.
The Repeat
palceholder represents one or multiple commands separated by a comma (,
); it is used to update the variable’s value, which is checked inside the Test Expression
part (a.k.a. Condition
part) of the loop. Considering the above code example, $i++
is the repeat section which increments the value of $i
by 1
using the increment operator represented by ++
. Remember, we can also write $i = $i+1
instead of $i++
but $i++
seems easier, reader-friendly and professional.
We used the Write-Host
cmdlet to print the value of $i
with a customized message. So, the above for
loop starts printing from 1
to 10
and exits from the loop as soon as i=11
. So, what is the execution flow of the for
loop?
- Initialization part will be executed.
- The condition will be evaluated.
- The script block (body of the
for
loop) will be executed if the condition is true. - The repeat part will be executed.
- The updated value will be checked via the specified condition.
- Now, steps
3
,4
, and5
will be repeated until the condition becomes false.
There is an alternate syntax for using the traditional for
loop, which is given below:
1 2 3 4 5 6 7 |
for ($i = 1 $i -le 10 $i++) { Write-Host "The Iteration Number is: $i" } |
1 2 3 4 5 6 7 8 9 10 11 12 |
The Iteration Number is: 1 The Iteration Number is: 2 The Iteration Number is: 3 The Iteration Number is: 4 The Iteration Number is: 5 The Iteration Number is: 6 The Iteration Number is: 7 The Iteration Number is: 8 The Iteration Number is: 9 The Iteration Number is: 10 |
We replaced the ;
with a new line in the above code snippet.
Use Multiple Commands in for
Loop Header
Use multiple commands in the header of the traditional for
loop, iterate 10
times and print a customized message on the PowerShell console.
1 2 3 4 5 |
for (($i = 0), ($j = 1); $i -lt 10 -and $j -le 10; $i++, $j++) { Write-Host "i = $i, j = $j" } |
1 2 3 4 5 6 7 8 9 10 11 12 |
i = 0, j = 1 i = 1, j = 2 i = 2, j = 3 i = 3, j = 4 i = 4, j = 5 i = 5, j = 6 i = 6, j = 7 i = 7, j = 8 i = 8, j = 9 i = 9, j = 10 |
This example is similar to the previous one, but we involved two variables, i
and j
, to use multiple commands in each section of the for
loop. We can also do Initialization
outside of the for
loop as follows:
1 2 3 4 5 6 7 |
$i = 0 $j = 1 for (; $i -lt 10 -and $j -le 10; $i++, $j++) { Write-Host "i = $i, j = $j" } |
1 2 3 4 5 6 7 8 9 10 11 12 |
i = 0, j = 1 i = 1, j = 2 i = 2, j = 3 i = 3, j = 4 i = 4, j = 5 i = 5, j = 6 i = 6, j = 7 i = 7, j = 8 i = 8, j = 9 i = 9, j = 10 |
Similarly, we can do the Repeat
section within the script block; see the following example.
1 2 3 4 5 6 7 8 9 |
$i = 0 $j = 1 for (; $i -lt 10 -and $j -le 10; ) { Write-Host "i = $i, j = $j" $i++ $j++ } |
1 2 3 4 5 6 7 8 9 10 11 12 |
i = 0, j = 1 i = 1, j = 2 i = 2, j = 3 i = 3, j = 4 i = 4, j = 5 i = 5, j = 6 i = 6, j = 7 i = 7, j = 8 i = 8, j = 9 i = 9, j = 10 |
We can also display a constant value or string (which does not change) for every iteration of the loop for an unlimited time until the user stops it. See the following example.
Unlimited Iterations using for
Loop
Omit all commands from the traditional for
loop header to iterate unlimitedly.
1 2 3 4 5 |
for (;;) { Write-Host "Welcome to Java2Blog!" } |
1 2 3 4 5 6 7 8 9 10 11 |
Welcome to Java2Blog! Welcome to Java2Blog! Welcome to Java2Blog! Welcome to Java2Blog! Welcome to Java2Blog! Welcome to Java2Blog! ... ... ... |
This time, we do not have any command enclosed within the ()
except two semicolons which results in unlimited execution of the script block wrapped around with {}
. It will continue printing Welcome to Java2Blog!
until the user presses Ctrl + C.
Let’s see another example where the value changes with each iteration but still runs for unlimited times until the user hits the Ctrl + C.
1 2 3 4 5 6 |
$i = 1 for (;;$i++ ) { Write-Host "i = $i" } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9 i = 10 i = 11 i = 12 i = 13 i = 14 ... ... ... |
Using ForEach
Loop
Use the ForEach
loop to print values from 1
to 10
on the PowerShell console.
1 2 3 4 5 6 |
$array = @(1,2,3,4,5,6,7,8,9,10) ForEach($i in $array){ Write-Host $i } |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
First, we created an array using the array operator (@()
) containing 10
integer values (one to ten), which we assigned to the $array
variable. Next, we used the ForEach
to loop over the $array
. Finally, we used the Write-Host
cmdlet in each iteration to print the current value from the $array
.
Remember, the ForEach
loop (a.k.a. ForEach
statement) is also used for traditional looping constructs for stepping through items in a collection, such as arrays. The ForEach
loop has two parts enclosed within ()
. In the first part, a variable is automatically created when PowerShell runs the ForEach
statement; in the above code, it was $i
. The second part is the collection ($array
) on which the loop will be iterated.
Unlike the for
loop, we can not directly have multiple commands in each part of the ForEach
header to work on various arrays or collections, but there is the other way around. So let’s see how we can do it.
Work with Multiple Arrays using ForEach
Loop
Use the Zip()
method to work with multiple arrays in the ForEach
loop and iterate 10
times.
1 2 3 4 5 6 7 8 9 10 11 12 |
$names = @("John", "Tony", "Andy", "Adam", "Henry", "Martin", "Sam", "Stoyan", "Nancy", "Paul") $ages = @(50, 30, 35,23,45,34,56,22,34,25) $zipped = [System.Linq.Enumerable]::Zip($names, $ages, [System.Func[object,object,object]]{ [Tuple]::Create($args[0], $args[1]) }) foreach ($tuple in $zipped) { Write-Host "$($tuple.Item1) is $($tuple.Item2) years old" } |
1 2 3 4 5 6 7 8 9 10 11 12 |
John is 50 years old Tony is 30 years old Andy is 35 years old Adam is 23 years old Henry is 45 years old Martin is 34 years old Sam is 56 years old Stoyan is 22 years old Nancy is 34 years old Paul is 25 years old |
First, we created two arrays, $names
having names and $ages
containing the ages of the students. Then, we must zip both arrays to work on $names
and $ages
within the ForEach
. Why are we zipping them? Because we can’t use multiple commands within the ForEach
header to iterate over $names
and $ages
. So, we used the Zip()
method of System.Linkq.Enumerable class to combine $names
and $ages
into tuples. Note that zipping both arrays will not modify the original arrays.
The Zip()
method took three arguments whose brief description is given below sequentially:
- The
$names
array that we want to zip with the second array. - The
$ages
array that we want to zip with the first array. - This argument is a delegate specifying how to combine
$names
and$ages
. In the above code, it is defined using the[System.Func[object, object, object]]
type representing that it will take twoobject
arguments and will return anobject
. It creates aTuple
object with two arguments ($args[0]
and$args[1]
) corresponding to the items of the two arrays being zipped.
We stored the tuple, returned by the Zip()
method, in the $zipped
variable, which was further passed to the ForEach
. Then, inside the ForEach
, we used the Write-Host
cmdlet to print customized messages.
Further reading:
Pipe Input to ForEach
Loop
Pipe input to the ForEach
loop to iterate from 1
to 10
in PowerShell.
1 2 3 4 5 6 |
$ages = @(1,2,3,4,5,6,7,8,9,10) $ages | ForEach{ Write-Host $_ } |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
Alternatively, we can do the above example as follows if creating an array is not mandatory.
1 2 3 4 5 6 |
$ages = 1..10 $ages | ForEach{ Write-Host $_ } |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
The ..
was used to create a range of numbers in PowerShell.
Unlimited Iterations using ForEach
Loop
There is no direct way to use ForEach
for unlimited iterations, but we can use while
with ForEach
to do infinite iterations; otherwise, a traditional for
loop can be used for this particular scenario (we have learned traditional for
in the first section).
1 2 3 4 5 6 7 8 |
$ages = @(50, 30, 35,23,45,34,56,22,34,25) while($true){ $ages | ForEach{ Write-Host $_ } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
50 30 35 23 45 34 56 22 34 25 50 30 35 23 45 34 56 22 34 25 ... ... ... |
Here, we did not specify the test condition for the while
loop to end but mentioned $true
within the ()
, which means the while
loop would always be True
and cause ForEach
loop’s execution for an unlimited time until the user hits Ctrl+C.
The
for
andForEach
loops are both traditional looping constructs, butForEach
is the simplest and easiest way to loop over a collection and can be used with the pipeline. On the other hand, using traditionalfor
is more straightforward thanForEach
while working with multiple arrays or commands.
Using ForEach-Object
Cmdlet
Use the ForEach-Object
cmdlet to loop from 1
to 10
in PowerShell.
1 2 3 4 5 6 |
$range = 1..10 $range | ForEach-Object { Write-Host $_ } |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
First, we specified a lower number before the ..
operator and an upper number after it. Then, we stored this range of numbers in the $range
variable, piped with the ForEach-Object
cmdlet to iterate over it and display one element on each iteration using the Write-Host
cmdlet. The ForEach-Object
cmdlet performs the given operation on each element of the collection of input objects.
Alternatively, we can do as follows:
1 2 3 |
1..10 | % { Write-Host $_ } |
1 2 3 4 5 6 7 8 9 10 11 12 |
1 2 3 4 5 6 7 8 9 10 |
Here, %
means for each object in the given range, which was 1..10
.
Remember, the
ForEach-Object
is only used when input data is piped to it.
Work with Multiple Arrays using ForEach-Object
Cmdlet
Use the ForEach-Object
cmdlet with -Begin
and -Process
parameters to work with multiple arrays and iterate 10
times.
1 2 3 4 5 6 7 8 9 10 |
$names = @("John", "Tony", "Andy", "Adam", "Henry", "Martin", "Sam", "Stoyan", "Nancy", "Paul") $ages = @(50, 30, 35,23,45,34,56,22,34,25) $names | ForEach-Object -Begin { $i = 0 } -Process { Write-Host "$($_) is $($ages[$i]) years old" $i++ } |
1 2 3 4 5 6 7 8 9 10 11 12 |
John is 50 years old Tony is 30 years old Andy is 35 years old Adam is 23 years old Henry is 45 years old Martin is 34 years old Sam is 56 years old Stoyan is 22 years old Nancy is 34 years old Paul is 25 years old |
After creating $names
and $ages
arrays, we piped the $names
to the ForEach-Object
cmdlet and used -Begin
and -Process
parameters to iterate over both arrays ($names
& $ages
) simultaneously.
Inside the -Begin
block, we set the $i
to 0
. Then, in the -Process
block, the current element from the $names
array was accessed in the pipeline using $_
and the corresponding age from $ages
using the $i
variable. Finally, we used Write-Host
to print those on the PowerShell console.
Unlimited Iterations using ForEach-Object
Cmdlet
Unlike the ForEach
loop, there is no direct way to use ForEach-Object
for unlimited iterations, but we can use while
with ForEach-Object
to do unlimited iterations; otherwise, traditional for
loop can be used for this use case.
1 2 3 4 5 6 7 8 |
$ages = @(50, 30, 35,23,45,34,56,22,34,25) while($true){ $ages | ForEach-Object{ Write-Host $_ } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
50 30 35 23 45 34 56 22 34 25 50 30 35 23 45 34 56 22 34 25 ... ... ... |
This loop will only end if the user presses Ctrl+C from the keyboard.
That’s all about PowerShell for loop 1 to 10.