PowerShell - 08.Loop

1 - For Loop
2 - Foreach Loop
3 - While Loop
4 - Do-while Loop
5 - Continue and Break Statement

For Loop

Example 1:
PS C:\> for($x=1; $x -lt 10; $x=$x+1) { Write-Host $x}
1
2
3
4
5
6
7
8
9
Example 2:
PS C:\> $a = @("A","B","C","D","E")
PS C:\> for($i = 0; $i -lt $a.length; $i++){$a[$i]}
A
B
C
D
E


Foreach Loop

Example 1:
PS C:\> $a = @("A","B","C","D","E")
PS C:\> foreach ($b in $a) { $b }
A
B
C
D
E
Example 2:
PS C:\> $a = @("A","B","C","D","E")
PS C:\> $a | foreach { $_ }
A
B
C
D
E


While Loop

Example 1:
PS C:\> while($count -le 5)  {  Write-Host $count; $count +=1 }

1
2
3
4
5


Do-while Loop

Example 1: 
PS C:\> $i=1
PS C:\> do
>> {
>> Write-Host $i
>> $i=$i+1
>> }
>> while ($i -le 10)
1
2
3
4
5
6
7
8
9

Save as Script_file1.ps1

$i=1
do
{
Write-Host $i
$i=$i+1
}
while ($i -le 10)


Continue and Break Statement

The Continue statement is used in PowerShell to return the flow of the program to the top of an innermost loop. This statement is controlled by the for, Foreach and while loop.

Example 1:
PS C:\> for($a=1; $a -lt 10; $a++)
>> {
>> if ($a -eq 6)
>> {
>> break
>> }
>> Write-Host $a
>> }
1
2
3
4
5
Example 2:
PS C:\> for($a=1; $a -lt 10; $a++)
>> {
>> if ($a -eq 6)
>> {
>> continue
>> }
>> Write-Host $a
>> }
1
2
3
4
5
7
8
9

Save as Script_file2.ps1

for($a=1; $a -lt 10; $a++)  
{  
if ($a -eq 6)
{
break
}
Write-Host $a
}

Save as Script_file3.ps1

for($a=1; $a -lt 10; $a++)
{
if ($a -eq 6)
{
continue
}
Write-Host $a
}
Previous Post Next Post