Powershell Loops
For Loops
For Loop (Using Counters)
For(InitValue; Comparison; Increment){ … }
$myFriends = @('Rob', 'Paul', 'Sam', 'Kyle')
For($counter=0; $counter -le ($myFriends.Length - 1); $counter++){
Write-Host $myFriends[$counter] "is my friend."
}
Note: Would have been better to use -lt and actual length instead of the extra math, but showing what can be done here. Ex: `$counter -lt $myFriends.Length;`
Foreach (Using array elements)
Foreach($value in $array){ … }
$myFriends = @('Rob', 'Paul', 'Sam', 'Kyle')
Foreach($friend in $myFriends){
Write-Host $friend "is my friend."
}
Do / While Loops
While($condition is true){ … }
$myFriends = @('Rob', 'Paul', 'Sam', 'Kyle')
$counter = 0
While($counter -lt $myFriends.Length){
Write-Host $myFriends[$counter] "is my friend."
$counter++
}
Do – While Loop
Will always run at least 1 time
$myFriends = @('Rob', 'Paul', 'Sam', 'Kyle')
$counter = 0
Do {
Write-Host $myFriends[$counter] "is my friend."
$counter++
} While($counter -lt $myFriends.Length)