Controlling Your Code's Flow with PowerShell's Control Statements

PowerShell Control Statements

Windows PowerShell provides several ways to control the flow of code. You can use conditional statements to define conditions and the actions to occur when those conditions are met. You can even specify the actions to occur when a condition isn’t met.

PowerShell Control statements can be broken down into three sections:

Conditional statements

Used when you want to execute line of code depending upon some condition.

Looping statements

Used when you want to perform some task multiple time.

Flow control statements

Used along with conditional and loop statements to control the flow of execution.


Lets go through all, one by one:

Conditional statements


if statement
- execute the script if condition evaluates to true.
elseif statement
- execute the script if condition evaluates to true and all if, elseif conditions before it false.
else statement
- execute the scripts that follows it when none of the conditions in if, elseif evaluates to true.

Syntax
                     if(condition 1) {
                             // Executes when the condition 1 is true
                             }elseif(condition 2) {
                             // Executes when the condition 2 is true
                             }elseif(condition 3) {
                             // Executes when the condition 3 is true
                             }else {
                             // Executes none of the condition is true.
                             }

Example 1:
                            $var = 20
                            if($var -lt 30)
                            {
                            Write-Host "value is less than 30"
                            }
                            else
                            {
                            write-host "value is more than 30"
                            }
Output: 

As value of $var is less than 30, condition with if statement evaluated to true and script within braces executed.

Example 2:
                            $occupation = "marketing"
                            if($occupation -eq "engineering")
                            {
                            write-host "engineering department"
                            }
                            elseif($occupation -eq "marketing")
                            {
                            write-host "marketing department"
                            }
                            else
                            {
                            write-host "accounting department"
                            }
Output: 

As condition along elseif block evaluated true, highlighted statement executed.

Switch statement
        - alternative for multiple if/ elseif/ else statements.

Syntax
                          Switch (<Value>)
                          {
                          <Condition1> {Action1}
                          <Condition2> {Action2}
                          }

Full Syntax:

                         Switch [-regex | -wildcard | -exact ] [ -casesensitive ]  ( <value> ) 
                         {
                          "String" | Number | Variable | { expression } {  action  }
                          default { default action }
                         }

Example 1:
                    $day = 5                      switch ( $day )                      {                  0 { $result = 'Sunday' }                 1 { $result = 'Monday' }                 2 { $result = 'Tuesday' }                 3 { $result = 'Wednesday' }                 4 { $result = 'Thursday' }                 5 { $result = 'Friday' }                 6 { $result = 'Saturday' }                     }                     $result
Output: 

Example 2:
                        $item = 'Role'
                        switch ( $item )
                        {
                        Component
                            {
                            'item is a component'
                            }
                        Role
                            {
                            'item is a role'
                            }
                        Location
                            {
                            'item is a location'
                            }
                        }
Output: 


A unique feature of PowerShell switch statement is that it has number of parameters that change how it performs. 

 -CaseSensitive

The matches are not case sensitive by default. If you need to be case sensitive then you can use -CaseSensitive. This can be used in combination with the other switch parameters.

-Wildcard

We can enable wildcard support with the -wildcard switch. This uses the same wildcard logic as the -like operator to do each match.

Example 3:
$Message = 'warning, out of disk space'
    switch -Wildcard ( $message )
    {
        'Error*'
        {
            Write-Error -Message $Message
        }
        'Warning*'
        {
            Write-Warning -Message $Message
        }
        default
        {
            Write-Information $message
        }
    }
Output: 

Here we are processing a message and then printing it on different streams based on the contents.
-Regex
The switch statement supports regex matches just like it does wildcards. If Regex is mentioned in switch, it evaluates the expression with passed value and if part of the condition matches then it executes that operation.
Example 4:
    
                Switch -Regex ("Donkey")
                    {
                    "Dog" 
                            {
                             "Dog is Mentioned"
                            }
                    "Cat" 
                            {
                             "Cat is Mentioned"
                            }
                    "Don" 
                            {
                            "Donkey is Mentioned"
                            }
                    "key" 
                            {
                            "Donkey is mentioned again"
                            }
                    default 
                            {
                             "Nothing is mentioned"
                            }
                    }

Output: 


Looping Statement 


While Loop
- code inside while loop will execute if condition evaluates true.

Syntax
                          while(condition)
                          {
                           Statement 1
                           Statement 2
                          }

Example:
                        $i = 1
                        while($i -lt 5)
                        {
                            Write-Host $i
                            $i++
                        }

Output: 
value of variable $i printed till condition is true means its value is less than 5.

Do While Loop
- Do while is similar to while loop only difference is it will execute at least once, that means it will execute do a block for the first time and while block if a condition is true.

Do: This block executes for first and once when execution starts.
While: Execution of statement 1 and statement 2 again totally depends on the success of the condition.

Syntax
Do
{
Statement 1
Statement 2
}
while(condition)

Example:
$j = 1
do
{
Write-Host $j
$j++
}while($j -lt 5)

Output: 
value of variable $j printed till condition is true means its value is less than 5.

For Loop
- code inside for loop will execute if condition evaluates true.

Syntax
for(init; condition; operation)
{
Statement 1
Statement 2
}
Init section: In this section, it assigned initial value for any variable, this section runs once for the first time.
Condition: In condition parts, we write our condition for which loop will run, which means the execution of statement block always depends on the success of condition parts if the condition is true then statement block will execute else not.
Operation: In this block, we can increase, decrease or change the value of the initializing a variable or any things according to our requirements.

Example:
for($i = 0; $i -lt 3; $i++)
{
Write-Host $i
}

Output: 
value of variable $i printed till condition is true means its value is less than 3.

Foreach Loop
- optimized version of For loop used to perform action for each item of array and
even you don’t need to write any code to extract items from array.

foreach($item in $arrayList)
{
Statement 1
Statement 2
}

Example:
$numbers = 1,2,3,4
foreach($number in $numbers)
{
“$number is now =“ +$number
}

Output:  

A typical use of the for loop is to operate on a subset of the values in an array. If you want to iterate all values in an array, consider using a foreach statement.

Many times one for loop is not enough to complete our requirements, so we can use nested for loops. We should try to avoid nesting of loops as their time complexity may go very high if not handled properly.

Flow Control Statement 


Break
- The break statement in PowerShell is used to terminate the loop. When the break statement is executed inside the inner loop, it terminates that loop execution and when
it is placed in the outer loop, it terminates the entire loop including child loop(s).

Examples
Break with while loop
                        $i=1
                        While($i -lt 10)
                        {
                            Write-Output "i = $i"
                            if($i -eq 5)
                            {
                            Write-Output "Break Statement executed"
                            break
                            }
                        $i++
                        }

Output:


Break with For loop
                        for($i=1;$i -lt 10 ; $i++)
                        {
                            Write-Output "i = $i"
                            if($i -eq 5)
                            {
                            Write-Output "Break Statement executed"
                            Break
                            }
                        }

Output: 

Continue
- Continue statement in PowerShell is used to skip the current execution of the loop and to return the execution to the top of the innermost loop. Continue statement is generally used with the conditional statement which is controlled by loops like While, For and Foreach. When the continue statement is executed inside the loop, it skips the current iteration and moves to the innermost loop for the next iteration.

Examples
Continue with while loop
                    $i = 0
                    while($i -lt 5)
                    {
                    $i++
                        if($i -eq 3)
                        {
                        write-host "skip"
                        Continue
                        }
                    Write-Host "i = $i"
                    } 

Output:
highlighted statement's execution skip as continue encountered when $i is equal to 3.

Break with For loop
                    for($i=1;$i -le 5; $i++)
                    {
                        if($i -eq 3)
                        {
                            write-host "skip"
                            Continue
                        }
                        Write-Host "i = $i"
                    

Output:

highlighted statement's execution skip as continue encountered when $i is equal to 3.

For live demo, go though below Youtube video:






Comments

Popular Posts

How to Import and Export Delimited Files, like CSV, in PowerShell

How to generate a GUID in PowerShell

PowerShell Arithmetic Operators