A piece of my work around PowerShell and IIS (or usefull things I've found on the web). Mostly some reminders for myself!

Here are the PS loop operators

 

# While Loop
While (condition)
<#
.EXAMPLE (try it!)
$i = 1
While ($i -le 10) {Write-Host "I'm testing loops with 'While'" -ForegroundColor DarkGreen; $i++}
.NOTES
PS: \>Measure-Command {.\loops.ps1} | Select TotalSeconds
TotalSeconds
------------
1.2661984
#>

# Do While Loop
Do
While (condition)
<#
.EXAMPLE (try it!)
$i = 1
Do {Write-Host "I'm testing loops with 'Do While'" -ForegroundColor DarkGreen; $i++}
While ($i -le 10)
.NOTES
PS: \>Measure-Command {.\loops.ps1} | Select TotalSeconds
TotalSeconds
------------
1.206995
#>

# Do Until Loop
Do
Until (condition)
<#
.EXAMPLE (try it!)
$i = 1
Do {Write-Host "I'm testing loops with 'Do Until'" -ForegroundColor DarkGreen; $i++}
Until ($i -eq 10)
.NOTES
PS: \>Measure-Command {.\loops.ps1} | Select TotalSeconds
TotalSeconds
------------
1.2143581
#>

# For Loop
For (initialization; condition; repeat)
<#
.EXAMPLE (try it!)
For ($i=1; $i -le 10; $i++)
{Write-Host "I'm testing loops with 'For'" -ForegroundColor DarkGreen;}
.NOTES
PS: \>Measure-Command {.\loops.ps1} | Select TotalSeconds
TotalSeconds
------------
1.1889838

# ForEach Loop
ForEach (
<#
.EXAMPLE (try it!)
$collection = @(1..1000)
ForEach ($i in $collection)
{Write-Host "I'm testing loops with 'ForEach'" -ForegroundColor DarkGreen;}
.NOTES
PS: \>Measure-Command {.\loops.ps1} | Select TotalSeconds
TotalSeconds
------------
1.1624701
#>

As you can see, there is not really one type of loop faster than another. So you’ll choose one type to be the easier to read the code or to the manage the condition.

Name*Email*WebsiteComment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top