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.The following loops will be demonstrated in this section:
- foreach
- for
- do
- while
The foreach loop is perhaps the most common of these loops.
foreach loop
The foreach
loop executes against each element of a collection using the following notation:
foreach (<element> in <collection>) {
<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 empty, the body of the loop will not execute.
ForEach keyword and ForEach alias
PowerShell comes with the alias foreach
for the ForEach-Object
command. When this alias acts depends on context.If foreach
is first in a statement, then the loop keyword is used.
$array = 1..3
foreach...