Loops#
ForEach-Object Cmdlet#
Foreach-Object is a cmdlet for processing data streams.
Foreach-Object is used for line-by-line processing of elements as they arrive in the input stream:
ForEach-Object -InputObject (Get-Process) -Process { $_ }
Get-Process | ForEach-Object { $_.Name }
Get-Process | % { $_.Name } # % is an alias for ForEach-Object
Get-Process | foreach { $_.Name } # alias for the foreach keyword
The break and continue operators do not work with ForEach-Object, as it is not a loop in the traditional sense, but rather an object processing pipeline.
Foreach Loop#
The Foreach loop is a loop for processing collections.
The foreach loop iterates over a collection:
foreach ($item in $array) {
# actions with $item
}
The continue operator skips the remaining part of the current iteration and moves to the next one.
The break operator completely terminates the loop.
To exit nested loops, you can use a label:
:outer foreach ($i in $array1) {
foreach ($j in $array2) {
if (<condition>) { break outer }
}
}
ForEach Method#
The ForEach() method in PowerShell is a method for collections (such as arrays, lists) that allows you to execute a specified script or action for each element of the collection. It is called on the collection object, takes a script block, and applies it sequentially to all elements, passing the current element to a special variable $PSItem (similar to $_ in pipelines).
$collection.ForEach({
# Here $PSItem is the current element of the collection
Write-Output $PSItem
})
This method is convenient when you need to perform an action for collection elements without using a foreach loop or the ForEach-Object cmdlet.
For Loop#
The For loop is a classic iterative loop.
The syntax is similar to C-like languages:
for (initialization; condition; action) {
# loop body
}
Example:
for ($i = 1; $i -le 10; $i++) {
Write-Host $i
}
The continue operator skips the remaining part of the current iteration and moves to the next one.
The break operator completely terminates the loop.
While and Do-While Loops#
The While loop is a precondition loop. While first checks the condition, then executes the body:
while ($a -le 10) {
$a++
}
The Do-While loop is a postcondition loop. Do-While first executes the body, then checks the condition:
do {
$i++
} while ($i -le 10)
Execution repeats as long as the condition is true.
The continue operator skips the remaining part of the current iteration and moves to the next one.
The break operator completely terminates the loop.
Do-Until Loop#
The Do-Until loop executes the body and then checks the condition for false:
do {
$i++
} until ($i -le 10)
It repeats the body while the condition is NOT met.
The continue operator skips the remaining part of the current iteration and moves to the next one.
The break operator completely terminates the loop.
Working with Loops#
You can find examples of usage at the link: