Loops in PowerShell

Introduction: The loops are part of any scripting language and PowerShell provides complete support for loops. Let’s see them with some examples

Foreach: This loop iterates through a collection and each value can be used further or just print to see the output.

#Example 1 - Prints the value
$CountryNames = @('India', 'UK', 'US', 'JAPAN', 'CANADA')
ForEach ($CountryName in $CountryNames )
      Write-Host "I live in $CountryName"

For: This loop iterates an array of items and can operate on the subset of these items

#Example 2 - Prints the value of an array
for($item = 0; $item -le 10; $item++)

ForEach-Object: This cmdlet operates on each item for the given collection. This input collection can be input through PowerShell Pipe or pass as a parameter.

#Example 3 - Prints the value of an array
$CountryNames = @("India", "UK", "US", "JAPAN", "CANADA")
$CountryNames | ForEach-Object {
        "I live in $_."

ForEach method: This PowerShell 4.0 ForEach method was added. This method method can be applied directly on the objects.

#Example 4 - Prints the value of an array
@ ("India", "UK", "US", "JAPAN", "CANADA").ForEach({$_})

Do-While loop: Do loop can be used when you always want to execute a code at least once. After executing first time, it checks for the conditions in While. There is another loop Do-Until loop. This loop always runs at least once before condition is evaluated. But, script executes only when Until condition is false.

#Example 5 - do-while print the number example
$count = 0
Do {
     "num $count"
} while ($count -ne 3)
#Example 6 - do-until print the number example
Do {
     "num $count"
} until ($count -eq 3)

The Continue and Break control flow can be used with loops like For, ForEach, While, Do-While and Do-Until.

Conclusion: So, this article covers frequently used loops and can be used to work with in the PowerShell.

Leave a Reply

Up ↑

%d bloggers like this: