How to loop through a PowerShell array

In this tutorial, we will discuss how to loop through an array in PowerShell using for loop. Also, we will see, PowerShell loop through an array using ForEach-Object loop, While loop, do-while loop, and do-until loop.

[toc]

If you are new to PowerShell, you can check the below tutorials:

Loop through PowerShell array using For Loop

Now, we will see how to loop through an array in PowerShell using for loop.

For ($i=0; $i -le 5; $i++) {
    "Number is: "+$i
    }

The above PowerShell array will print the numbers starting from 0 to 5.

PowerShell loop through array

In the case of a for loop, you will set up the value of a variable and then there will be a condition on which the loop will be terminated.

Below is the another example of a string array, below is how we can loop through a string array using for loop in PowerShell.

$employees = @("Bijay","Bhawana","Padmini","Lakshmi")
For ($i=0; $i -lt $employees.Length; $i++) {
    $employees[$i]
    }

The above array will print all the names from the array like below:

PowerShell loop through string array

PowerShell array foreach loop

Now, we will see how to loop through an array using foreach loop in PowerShell.

Syntax:

ForEach (item In collection) {code block}

Here item represents the current item, collection is the item collection.

Example:

$numbers=1,2,3,4,5
foreach ($num in $numbers) {
  $num;
 }

You can see the output like below:

powershell array foreach method

Now, we will see how to loop array of strings using PowerShell using foreach loop.

$employees = @("Bijay","Bhawana","Padmini","Lakshmi")
foreach ($emp in $employees) {
  $emp;
 }

You can see the output look like below:

powershell foreach loop string array

PowerShell While Loop

Now, we will see how to use while loop in PowerShell arrary.

Syntax:

while (condition) {code block}

Example:

$i=1
While ($i -le 5)
    {
    $i
    $i++
    }

You can see the output like below:

powershell loop array while loop

PowerShell array do-while loop

Now, we will see how to use do-while loop to loop through a PowerShell array.

$i=1
Do {
    $i
    $i++
    }
While ($i -le 5)

You can see the output like below:

powershell loop array do-while loop
powershell loop array do-while loop

Loop through PowerShell array using Do-Until loop

Now, we will see how to loop through a PowerShell array using the do-until loop.

$i=1
Do {
    $i
    $i++
    }
Until ($i -gt 5)

You can see the output looks like below:

powershell loop array do-until loop

In this tutorial we learned how to loop through an array using for look, foreach loop, while loop, do while loop, do until loop in PowerShell.

>