In this post we will be going through the different types of loops in PowerShell.
There are a few different types of loops and we will go through each and showing examples on how to use them. Loops are very useful and will be required in most scripts.
The first we will go through is a ForEach-Object loop, this is one of the main loops I use and can be used a few different ways.
Foreach Objects
First way is to get a list of objects and then pipe to our foreach-object to go through each.
Below example will get all services, loop through the results and return each name.
Get-Service | ForEach-Object { $_.Name}
Another method for using foreach-object is to use a variable with a set of object or a command that will retrieve objects and loop through each object in the variable.
There are two short hand commands for foreach-object, % and foreach.
In the below I am getting all folders under the directory and adding them to a $folders variable and looping through each.
$folders = Get-ChildItem C:\temp\ -Directory
foreach ($folder in $folders){$folder | Select-Object Name,CreationTime}
We can also use the foreach method on the variable to loop through the objects.
I mostly use foreach in my scripts as I find it the easiest to read when I have to go back over my own scripts.
While Loops
The other type of loops is a while loop.
Do while basically mean that while a condition is true the script will then keep looping.
This can be useful if we want to run a script for a certain period of time or while a process is running.
Below will loop through till the number in the variable $i is 10 then it will run the second write host.
$i = 1;
Do {
Write-host "is $i less then 10" -ForegroundColor Red
$i++;
}
While ($i -lt 10)
Write-Host "is 10 or greater" -ForegroundColor Green
Next we will go through do until, the different between do while and do until is that while uses true and until uses false condition.
This could be used if we wanted to check if a certain number of files or in an install script we could wait for certain process to finish before completing the next part.
Below example I am using a do until on a folder to check how many logs are there and using a do while to create the logs.
Check logs count.
Do {
$logs = Get-ChildItem -Path C:\temp\Logs
Start-Sleep 5
Write-Host "Less than 10 logs found" -ForegroundColor Green
}
Until ($logs.count -gt "10" )
Write-Host "More than 10 logs found" -ForegroundColor Red
Create logs files.
$i = 1;
Do {
New-Item "C:\temp\Logs\Log$i.log"
$i++;
}
While ($i -lt 10)
This has been overview of some of the different types of loops and how to use them. There are pros and cons to using each and the right one to use will really depend on what the script is being used for.