Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

7.4 Visit Each Element of an Array

Problem

You want to work with each element of an array.

Solution

To access each item in an array one by one, use the ForEach-Object cmdlet:

PS > $myArray = 1,2,3
PS > $sum = 0
PS > $myArray | ForEach-Object { $sum += $_ }
PS > $sum
6

To access each item in an array in a more script-like fashion, use the foreach scripting keyword:

PS > $myArray = 1,2,3
PS > $sum = 0
PS > foreach($element in $myArray) { $sum += $element }
PS > $sum
6

To access items in an array by position, use a for loop:

PS > $myArray = 1,2,3
PS > $sum = 0
PS > for($counter = 0; $counter -lt $myArray.Count; $counter++) {
    $sum += $myArray[$counter]
}

PS > $sum
6

Discussion

PowerShell provides three main alternatives to working with elements in an array. The ForEach-Object cmdlet and foreach scripting keyword techniques visit the items in an array one element at a time, whereas the for loop (and related looping constructs) lets you work with the items in an array in a less structured way.

For more information about the ForEach-Object cmdlet, see Recipe 2.5.

For more information about the foreach scripting keyword, the for keyword, and other looping constructs, see Recipe 4.4.

See Also

Recipe 2.5, “Work with Each Item in a List or Command Output”

Recipe 4.4, “Repeat Operations with Loops”