PowerShell: Loop, Iteration

By Xah Lee. Date: . Last updated: .

“For” Statement

for statement is useful if you also need the index of the array.

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

“While” Statement

while statement is most useful if you need to test a condition before the loop.

$a = 0..9
while($i -lt 10) {
  $a[$i]; $i++
# prints 5 to 9

“Foreach” Statement

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

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

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

ForEach-Object Cmdlet

ForEach-Object Cmdlet is most useful when you need to pipe to it. The input can be a array type or collection.

ForEach-Object ScriptBlock
Example: dir | ForEach-Object {$_.fullname}

Loop, Iteration