If, ElseIf And Else
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 13 of 28.
if runs a block of code only when its condition is True. The condition goes in parentheses and the block in braces:
$battery = [int](Read-Host "Battery")
if ($battery -lt 10) {
Write-Output "Charge now"
} elseif ($battery -lt 50) {
Write-Output "Charge soon"
} else {
Write-Output "Battery is fine"
}PowerShell tests the conditions from the top and runs the first block whose condition is True; the others are skipped. else runs when no condition matched. With the input 30, this prints Battery: 30 and Charge soon: 30 is not below 10, but it is below 50.
Because the first match wins, put the narrowest test first. You can have any number of elseif blocks and at most one else.
To join two conditions, use -and (both must be True) or -or (one is enough); -not turns True into False: if ($battery -ge 50 -and $battery -lt 80).
Challenge
EasyRead a temperature in degrees Celsius and describe it.
- Read a whole number with the prompt
Temperature. - Print
Freezingbelow 0,Coldfrom 0 up to 14,Warmfrom 15 up to 24 andHotfrom 25 up.
With the input 14, your script prints:
Temperature: 14
ColdWith 15, the second line is Warm, and with -5 it is Freezing.
Try it yourself
$t = [int](Read-Host "Temperature")
# Print Freezing, Cold, Warm or Hot
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check3Input And Conditions
Reading InputComparison OperatorsIf, ElseIf And ElseThe Switch StatementRecap - Ticket Price