Scripting, flow control (if-elseif-else, while loop, do-while loop, for loop, break and continue, switch)

Scripting, flow control (if-elseif-else, while loop, do-while loop, for loop, break and continue, switch)

If ( ) … elseif ( ) … else { }

Syntax:

if ( condition ) { commands_to_execute }

[ elseif ( condition2 ) { commands_to_execute } ]

[ else { commands_to_execute } ]

if(2 -eq 2)
{
    Write-Host "True"
}
else
{
    Write-Host "False"
}

The output of above script will be “True”.

if(2 -eq 5)
{
    Write-Host "True"
}
else
{
    Write-Host "False"
}

The above script will print “False”.

Example of if-elseif-else :

$os = Get-WmiObject win32_operatingsystem
if ($os.Caption -match "2003")
{
	Write-Host "Windows Server 2003"
}

elseif ($os.Caption -match "2008")
{
	Write-Host "Windows Server 2008"
}

else
{
	Write-Host "Neither Windows 2003 nor Windows 2008"
}

while loop:

Syntax
while (condition) {command_block}

$a = 1

while ($a -lt 6)
{
	Write-Host $a
	$a++
}

1
2
3
4
5

do-while loop:

Syntax:

Do { command_block while (condition)

do
{
    Write-Host $a
    $a++
}
while ($a -le 10)

1
2
3
4
5
6
7
8
9
10

for Loop:

Syntax
for (init; condition; repeat)
{command_block}

for($a=1; $a -le 10; $a++)
{
     Write-Host $a
}

1
2
3
4
5
6
7
8
9
10

break

Break is used to exit a loop immediately.

Break can also be used to stop script execution when it is placed outside a loop or switch statement.

In a For, ForEach, While, Do loop or in a Switch statement you can add a break statement to exit each code block.

Example:

for($i = 1; $i -le 10; $i++)
{
    if($i -eq 5) {break}
    $i;
}

The output of the above code will be as follows:

1
2
3
4

continue

Return to top of a program loop, skip just this iteration of the loop.

for ($i = 1; $i -le 10; $i++)
{
    if ($i -eq 5) { continue }
    $i;
}

The output of the above code will be as follows:

1
2
3
4
6
7
8
9
10

Let us see how we can use continue statement for printing odd numbers from 1 to 10.

for($i = 1; $i -le 10; $i++)
{
    if($i%2 -eq 0) {continue}
    $i;
}

And here is the output:

1
3
5
7
9

switch

switch ($fruit)
{
    "Apple" {echo "Apple is my favorite fruit!"; break}
    "Orange" {echo "Orange is my favorite fruit!"; break}
    "Mango" {echo "Mango is my favorite fruit!"; break}
    default {echo "This is default statement"; break}
}

The put will be as per the value of $fruit. If no value is assigned to $fruit, or not equal to any of the cases, it will print the default.

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on reddit
Share on skype
Share on telegram
Share on whatsapp
Share on email
Share on print

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment