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.