PowerShell CheatSheet – Loops reminder

Here are the PS loop operators

# While Loop
While (condition) {code_block}
<#
.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 {code_block}
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 {code_block}
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)
{code_block}
<#
.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 ($<collection_item> in $<collection>)
{code_block}
<#
.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.

Leave a Reply

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

Scroll to Top