Introduction
If-elseif-else statements help your script make choices. They run different code based on conditions.
If-elseif-else statements help your script make choices. They run different code based on conditions.
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.
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." }
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" }
This script checks the temperature and prints a message about the weather.
$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." }
PowerShell uses -ge for 'greater than or equal to' in conditions.
Always use curly braces { } to group the code for each condition.
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.
if-elseif-else statement do in PowerShell?$num = 7
if ($num -lt 5) {
'Less than 5'
} elseif ($num -eq 7) {
'Equal to 7'
} else {
'Other'
}
if $value -gt 10 {
'Greater than 10'
} elseif ($value -eq 10) {
'Equal to 10'
} else {
'Less than 10'
}Pass the test and this pattern moves unknown