Skip to main content

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 onebyone, use the ForeachObject cmdlet:

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

To access each item in an array in a more scriptlike 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 ForeachObject cmdlet and foreach scripting keyword techniques visit the items in an array one element at a time, while the for loop (and related looping constructs) lets you work with the items in an array in a less structured way.

Process and iterate through array elements efficiently with PowerShell on a United Kingdom Dedicated Server, providing dedicated resources, reliable performance, and full administrative control for handling server data and automating administrative tasks.

Help Category