0
0
PowerShellscripting~5 mins

If-elseif-else statements in PowerShell

Choose your learning style9 modes available
Introduction

If-elseif-else statements help your script make choices. They run different code based on conditions.

Check if a file exists and do something if it does or doesn't.
Decide what message to show based on a user's input.
Run different commands depending on the time of day.
Choose an action based on a number's value.
Syntax
PowerShell
if (<condition1>) {
    # code to run if condition1 is true
} elseif (<condition2>) {
    # code to run if condition2 is true
} else {
    # code to run if none of the above conditions are true
}

Conditions are expressions that result in True or False.

Use elseif for multiple checks after the first if.

Examples
This checks age and prints a message for adult, teenager, or child.
PowerShell
if ($age -ge 18) {
    Write-Output "You are an adult."
} elseif ($age -ge 13) {
    Write-Output "You are a teenager."
} else {
    Write-Output "You are a child."
}
This assigns a grade based on the score value.
PowerShell
if ($score -ge 90) {
    Write-Output "Grade: A"
} elseif ($score -ge 80) {
    Write-Output "Grade: B"
} elseif ($score -ge 70) {
    Write-Output "Grade: C"
} else {
    Write-Output "Grade: F"
}
Sample Program

This script checks the temperature and prints a message about the weather.

PowerShell
$temperature = 75

if ($temperature -ge 85) {
    Write-Output "It's hot outside."
} elseif ($temperature -ge 65) {
    Write-Output "The weather is nice."
} else {
    Write-Output "It's cold outside."
}
OutputSuccess
Important Notes

PowerShell uses -ge for 'greater than or equal to' in conditions.

Always use curly braces { } to group the code for each condition.

Summary

If-elseif-else lets your script choose what to do based on conditions.

Use if for the first check, elseif for extra checks, and else for the default case.

Conditions must be true or false expressions.