PowerShell: Iterate Array

By Xah Lee. Date: . Last updated: .

here's ways to iterate over Array

Cmdlet: ForEach-Object

ForEach-Object cmdlet is most useful when you need to Pipe a collection to it.

(ForEach-Object has alias %, foreach)

syntax:

ForEach-Object ScriptBlock

@( 1..7 ) | ForEach-Object {$_}

Statement: Foreach

foreach-statement is useful when you want to go thru all the values of collection.

foreach-statement must be on a single line, when used in PowerShell prompt.

$aa = 1..9
foreach ($x in $aa) { echo $x }
# prints 1 to 9

Statement: for

for-statement is useful when you need both the element value and its index.

$aa = 1..9
for ($i=0; $i -le $aa.length; $i=$i+1) { $aa[$i] }
# prints 1 to 9

Statement: while

while-statement is useful when you need to exit the loop when a condition is satisfied.

$aa = 1..9
$i = 0;
while ($i -lt 5) {
    Write-Host $aa[$i];
    $i++
}
# prints 1 to 5

PowerShell Intrinsic Method: ForEach

ForEach is a hidden “intrinsic member” that PowerShell adds to every object.

syntax:

arrayX.ForEach(script_block)

iterate over array. In the script block, $_ is the value of current element.

$aa = 0..3
$aa.foreach({$_ + 1})

PowerShell: Loop, Iteration

PowerShell: Array