24/7/365 Support

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.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say