PowerShell: Loop, Iteration

By Xah Lee. Date: . Last updated: .

For Statement

for loop 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 loop is most useful if you need to test loop condition before the loop.

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

Foreach Statement

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

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

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

ForEach-Object Command

Syntax:

script block
example Get-ChildItem | ForEach-Object {$_.fullname}
Operation statement
example Get-ChildItem | ForEach-Object fullname

PowerShell

How-to

Advanced

Script Examples