Loops
Loops may be used to iterate through collections, performing an operation against each element in the collection; or to repeat an operation (or series of operations) until a condition is met.
Foreach
The foreach
loop executes against each element of a collection using the following notation:
foreach (<element> in <collection>) { <body-statements> }
For example, the foreach
loop may be used to iterate through each of the processes returned by Get-Process
:
foreach ($process in Get-Process) { Write-Host $process.Name }
If the collection is $null
or empty, the body of the loop will not execute.
For
The for
loop is typically used to step through a collection using the following notation:
for (<intial>; <exit condition>; <repeat>){ <body-statements> }
Initial
represents the state of a variable before the first iteration of the loop. This is normally used to initialize a counter for the loop.
The exit condition must be true
as long as...