In this article, I show you how to write a PowerShell loop. Like any other programming language, PowerShell also has different types of loops like – for loop, foreach loop, while loop and do while. Using these loops you can iterate the collection.
So let’s see how to use these PowerShell loops one by one.
1.PowerShell for loop
PowerShell 1..10 loop using for loop –
Example 1-
The below script prints 1 to 10 on the console using the PowerShell Write-Host command.
# loop through a range of numbers for ($i = 1; $i -le 10; $i++) { # code to execute Write-Host $i }
Example 2-
The below PowerShell loop iterate numbers from an array and prints on the console.
# loop through an array $numbers = 1, 2, 3, 4, 5 for ($i = 0; $i -lt $numbers.Length; $i++) { # code to execute Write-Host $numbers[$i] }
Example 3-
The below PowerShell loop iterate item from the Get-Service collection.
# loop through the items in a collection $services = Get-Service for ($i = 0; $i -lt $services.Count; $i++) { # code to execute Write-Host $services[$i].Name }
2.PowerShell foreach loop
The below example iterate numbers and collection using PowerShell foreach loop-
Example 1 –
Print PowerShell 1…10 numbers in the console using foreach loop-
# loop through a range of numbers $numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 foreach ($number in $numbers) { # code to execute Write-Host $number }
Example 2 –
Iterate collection using PowerShell foreach loop
# loop through the items in a collection $services = Get-Service foreach ($service in $services) { # code to execute Write-Host $service.Name }
3.PowerShell while loop
Print 1…10 number using PowerShell while loop
# loop while a condition is true $i = 1 while ($i -le 10) { # code to execute Write-Host $i $i++ }
4.PowerShell do-while loop
The below PowerShell script print 1..10 in the console using a PowerShell do-while loop.
# loop while a condition is true $i = 1 do { # code to execute Write-Host $i $i++ } while ($i -le 10)
That’s it these are some examples of PowerShell loops.
Conclusion
These loops are useful when you have to iterate items from a collection. This is how you can use the different types of PowerShell loops in your script.