PowerShell: Loop, Iteration
Cmdlet: ForEach-Object
ForEach-Object
Cmdlet is most useful when you need to pipe to it.
The input can be any collection type.
ForEach-Object
has alias:%
,foreach
syntax:
ForEach-Object ScriptBlock
Get-ChildItem | ForEach-Object {$_.fullname}
Statement: Foreach
foreach-statement is useful when you want to go thru all the values of a collection.
foreach statement must be on a single line, when used in PowerShell prompt.
$aa = 1..9 foreach ($x in $aa) { Write-Host $x } # prints 1 to 9
Statement: For
for-statement is useful if you also need the index of the collection.
$aa = 0..9 for ($i=0; $i -le $aa.length; $i=$i+1) { $aa[$i] } # prints 0 to 9
Statement: While
while-statement is most useful if you need to test a condition before the loop.
$a = 0..9 $i=5 while($i -lt 10) { $a[$i]; $i++ } # prints 5 to 9