Looping
for / foreach / while / do…while / do…until / Flow control
for
Syntax
:loop_label for (initialization; condition; increment) {
statement_block
}
Example
PS> $array = 1..3
PS> for ($i = 0; $i -lt $array.Count; $i++) {
>> Write-Host ($array[$i] * 2)
>> }
>>
2
4
6
foreach
Syntax
:loop_label foreach (variable in expression) {
statement_block
}
Example
PS> $array = 1..3
PS> foreach ($item in $array) {
>> Write-Host ([Math]::Pow($item,2))
>> }
>>
1
4
9
while
Syntax
:loop_label while (condition) {
statement_block
}
Example
PS> $command = ""
PS> while ($command -notmatch "quit") {
>> $command = Read-Host "Enter your Command"
>> }
>>
Enter your Command: a
Enter your Command: quit
PS>
do…while
Syntax
# do...while
:loop_label do {
statement_block
} while (condition)
Example
PS> $command = ""
PS> do {
>> $command = Read-Host "Please quit"
>> } while ($command -ne "quit")
>>
Please quit: a
Please quit: quit
PS>
do…until
Syntax
# do...until
:loop_label do {
statement_block
} until (condition)
Example
PS> $command = ""
PS> do {
>> $command = Read-Host "Please quit"
>> } until ($command -ne 'quit')
>>
Please quit: quit
Please quit: a
PS>
Flow control
Without a label, simply exit the inner loop.
:outer while(conditions){
while(conditions){
if(conditions){break}
}
}
With a label, it exits the loop with the label.
:outer while(conditions){
while(conditions){
if(conditions){break outer}
}
}
Example Without label
PS> $array = 1..3
PS> $limit = $array[-1]
PS> :outer foreach ($y in $array) {
>> foreach ($x in $array) {
>> if ($x -eq $limit) {
>> Write-Host "limit break"
>> break
>> }
>> Write-Host $x $y
>> }
>> }
>>
1 1
2 1
limit break
1 2
2 2
limit break
1 3
2 3
limit break
Example With label
PS> $array = 1..3
PS> $limit = $array[-1]
PS> :outer foreach ($y in $array) {
>> foreach ($x in $array) {
>> if ($x -eq $limit) {
>> Write-Host "limit break"
>> break outer # Different here!
>> }
>> Write-Host $x $y
>> }
>> }
>>
1 1
2 1
YouTube
Click here for a video explanation.