Tinus EngOps Wiki

Logo

OpsaC - Operating as PowerShell code

Links

Home

PowerShell Blog

PowerShell Index

PowerShell Search

Additional Websites

View my GitHub Profile

View my GitHub Gists

View Tinus IT Wiki

View my Photo Website

Loops

published: February 5, 2019 author: Tinu tags: PowerShell categories: PowerShell-Basic


Table of Contents

For-Loop

This example initializes the loop counter $i with the value 0. It increments the counter by one with each iteration until it reaches 5, which is the condition that quits the loop.

Initialize: $i = 0, Increment: $i++, Condition: $i -lt 5

for ($i = 0; $i -lt 5; $i++){
    Write-Host "Loop $($i), wait 2 Seconds"
    Start-Sleep -Seconds 2
}
$i = $null

While-Loop

It is called a pretest ($i -lt 5) loop because the instructions in the loop body are not executed, even once, if the loop condition doesn’t match.

Initialize: $i = 0, Increment: $i++, Condition: $i -lt 5

$i = 0
while ($i -lt 5) {
    Write-Host "Loop $($i), wait 2 Seconds"
    Start-Sleep -Seconds 2
    $i++
}

Do-While-Loop

From a syntactical point of view, do-while and do-until are identical. The difference is logical in nature.

do-while continues to run as long as the condition is true and terminates when the condition is no longer fulfilled.

do {
    $sc = Get-Service MyService
    if($sc.Status -notmatch 'Running'){
        Start-Service MyService
        Start-Sleep -Seconds 2
        $sc = Get-Service MyService
    }
}
while ($sc.Status -match 'Stop') ## if condition is true, go to the next loop

Do-Until-Loop

do-until works the other way around: it quits when the condition takes the value TRUE.

$i = 0
do {
    Restart-Computer MyServer
    Start-Sleep -Seconds 2
    $PsNetPing = Test-PsNetPing MyServer
    $i++
    if($i -gt 10){
        break
    }
}
until ($PsNetPing.IcmpSucceeded) ## if condition is true, exit the loop
if($i -gt 10){
    Write-Host "Break loop, could not start MyServer within $(2*10) seconds"
}else{
    Write-Host "MyServer is online"
}

ForEach-Loop

The conventional foreach loop is significantly faster than the ForEach-Object loop.

foreach($item in $collection) {
    Write-Host "Loop $($item), wait 2 Seconds"
    Start-Sleep -Seconds 2
}

ForEach-Object-Loop

Get-ADUser -Filter * | ForEach-Object {
    Write-Host $_
}

Timer-Loop

A short timer loop for one minute.

1..60 | foreach {write-host '.' -nonewline;sleep -Seconds 1}

See also

Loops in PowerShell on 4sysops


← Previous Post [ Top ] Copyright © 2024 by tinuwalther [ Blog ] Next Post →