Adjust Script Flow Using Conditional Statements

1. Problem

You want to control the conditions under which PowerShell executes commands or portions of your script.

2. Solution

Use PowerShell’s if, elseif, and else conditional statements to control the flow of execution in your script.

For example:

Code View: Scroll / Show All

        $temperature = 90
        
        if($temperature -le 0)
        {
           "Balmy Canadian Summer"
        }
        elseif($temperature -le 32)
        {
           "Freezing"
        }
        elseif($temperature -le 50)
        {
           "Cold"
        }
        elseif($temperature -le 70)
        {
           "Warm"
        }
        else
        {
           "Hot"
        }
 
 
                                        



3. Discussion

Conditional statements include the following:

if statement

Executes the script block that follows it if its condition evaluates to true

elseif statement

Executes the script block that follows it if its condition evaluates to true, and none of the conditions in the if or elseif statements before it evaluate to true

else statement

Executes the script block that follows it if none of the conditions in the if or elseif statements before it evaluate to true

For more information about these flow control statements, type Get-Help About_Flow_Control.

Tags: , , , , , ,