PowerShell allows you to control the flow of your scripts through several different looping options. Below are some examples of what types of loops to use.
For loop:
- Controls execution of code while a condition is true.
- Usually used to perform a action a certain number of times.
Example:
For ($i = 1; $i –le 10; $i++) {Write-Host “Loop index is at $i”}
While
- Runs while a condition is true.
Example
$Val=0
while($Val -ne 3)
{
$val++
Write-Host $val
}
Do While
- Evaluates a condition before running code.
- If the condition is false, the code will not run.
Example
$Index = 10
Do {$index--
Write-Host "$Index"
} while ($Index -gt 0)
Do Until
- Evaluates the condition after the code has run once.
- Loops through the code until a condition becomes true.
- Ensures that the code will be run at least once before the loop terminates.
Example
$Str = "My Text String"
do {
$str = $str.remove($str.length - 1)
write-host $str
} until ($str.length -lt 3)
Comments