An if
statement tests for a condition and takes action if the condition is true, but what if we want to do something if the condition is false? This is where else
can be used:
$myVar = 2 if($myVar -lt 0) { Write-Host "A negative number" } else { Write-Host "A positive number" }
The above example uses else
after the initial if
statement body. Curly braces after the else
defines another body that contains the code to be executed if the condition is false.
else
captures all other scenarios not met by your if
statement. We can now define specific behaviors based on a true or false condition.
Depending on our situation, we may need to account for multiple conditions at a specific point in our code. This is where we could utilize the elseif
conditional statement:
$myVar = 2 if ($myVar -lt 0) { Write-Host "A negative number" } elseif ($myVar -gt 0) { Write-Host "A positive number" } else { Write-Host "Zero" }
This example has two conditions to check. If the first condition, $myVar -lt 0
, is false, the script moves on to the elseif
with another condition in parentheses. If the second condition, $myVar -gt 0
, is true, the code inside the body is run. The else
body is executed if both conditions are false.
We can add as many elseif
statements to an if
statement as long as an else
statement remains the final statement.
Instructions
ELSEIF_example.ps1 contains a variable definition and an if
statement.
Do you think there will be any output? Click Run to find out.
Add an elseif
statement to check if $var
is greater than 5
. If the condition is true, output your own message.
Will there be output?
Add another elseif
statement to check if $var
is greater than 0
. Output another message inside this body.
Will you see any output now?
Lastly, use an else
statement if none of those conditions are met. Output one more message inside this body.
Once complete, you can change the value of $myvar
to see the different output from each condition check.