How to Loop Through an Array in PowerShell?

You might want to loop through a PowerShell array. In this PowerShell tutorial, I will explain different methods to loop through an array in PowerShell.

To loop through an array in PowerShell, you can use a foreach loop. First, declare your array, then use foreach ($element in $yourArray) to iterate over each item. Inside the loop, $element represents the current item in the array, allowing you to perform actions or calculations on it.

What is an Array?

An array is a data structure that stores a collection of items. In PowerShell, arrays can hold multiple items of the same or different types. You can create an array by assigning multiple values to a variable, separated by commas.

$myArray = "apple", "banana", "cherry"

Now, let us check out the different ways to loop through an array using various methods.

Looping through an Array with a For Loop

A for loop in PowerShell is used for iterating a set number of times. It’s useful when you know exactly how many times you want to loop through the array.

$myArray = "Chicago", "Phoenix", "Los Angeles"

for ($i = 0; $i -lt $myArray.Length; $i++) {
    Write-Host $myArray[$i]
}

In this example, $i is the loop variable that starts at 0 and increments by 1 on each iteration of the loop. The loop runs as long as $i is less than the length of the array. Here is the output you can see the output after I executed the PowerShell script using VS Code.

Loop Through an Array in PowerShell

Looping with a Foreach Loop

The foreach loop is one of the most common ways to iterate through an array in PowerShell. It’s simpler than a for loop because it handles the iteration for you without the need to define and manage a loop counter.

$myArray = "Chicago", "Phoenix", "Los Angeles"

foreach ($item in $myArray) {
    Write-Host $item
}

In this example, $item represents the current element in the array for each iteration of the loop.

You can see the output in the screenshot below after I executed the PowerShell script using VS code.

powershell loop array

Using the ForEach-Object Cmdlet

PowerShell also provides the ForEach-Object cmdlet, a pipeline-based method for iterating over each item in an array or collection.

$myArray = "Chicago", "Phoenix", "Los Angeles"

$myArray | ForEach-Object {
    Write-Host $_
}

Here, $_ is a special variable that represents the current object in the pipeline.

You can see the output in the screenshot below after I executed the code using Windows PowerShell ISE.

powershell loop through array

Conclusion

Looping through arrays in PowerShell can be done using various methods, each with its own use case. For beginners, the foreach loop is often the easiest to understand and implement. In this PowerShell tutorial, I have explained, how to loop through an array in PowerShell using the below methods:

  • Using For Loop
  • Using Foreach Loop
  • Using ForEach-Object Cmdlet

You may also like: