OpsaC - Operating as PowerShell code
published: February 5, 2019 author: Tinu tags: PowerShell categories: PowerShell-Basic
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
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++
}
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 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"
}
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
}
Get-ADUser -Filter * | ForEach-Object {
Write-Host $_
}
A short timer loop for one minute.
1..60 | foreach {write-host '.' -nonewline;sleep -Seconds 1}
Loops in PowerShell on 4sysops