PowerShell Loop Hands-On


Arrays and loops are often used including when working with PowerShell scripts.

In the following example, 4 array values are created, these are called again by means of the ID.

An array is created with the following command:
Output values with For-Loop Array:

The length of the array, or the number of stored values, is read out with $array.length. The variable ($i) serves as a counter to count when to exit the loop. A start value is assigned to the counter ($i=0).The start value should increase by 1 each time the loop passes ($i++) until the final value is reached. The final value is the length of the array ($array.length). When checking the final value, there is a condition: as long as $i is less than the number of values ($i -lt $array.length).

PowershellFor loop

The For loop: for ($i=0; $i -lt $array.length; $i++)
Start value $i=0: The variable $i starts with a value of 0
is $i smaller (-lt) $i -lt $array.length condition: the For loop is executed as long as this condition is met: as long as the variable $i is less than $array.length, so as long as $i is less than 4. The action at the loop pass: $i++ means to increase the value of the variable $i by 1, with each pass of the loop $i increases by 1: 0 .. 1 .. 2 .. 3 …

while loop

Example with starting value $i defined before the loop ($i=0)
while ($i -lt $array.length)
Within while is the condition for the loop pass, which loop wid does not leave as long as it is fulfilled:
$i -lt $array.length … as long as $i is smaller $array.length
The variable $i is incremented by 1 within the loop: $i++

Endless Loop

while can be used for an infinite loop as follows: with break, the infinite loop can be exited again. The following example goes through the loop until break is executed, this happens when $i is no longer less than 10:

do loop

foreach ($i in $array) call all values of the array ($array). The variable $i contains the currently read value for each pass.


-eq is equal
-ne is not the same
-gt is greater than
-ge is greater or equal
-lt is smaller than
-le is less or equa

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *