Menu
CoddyTech

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 icon

Challenge

Easy

Read a temperature in degrees Celsius and describe it.

  1. Read a whole number with the prompt Temperature.
  2. Print Freezing below 0, Cold from 0 up to 14, Warm from 15 up to 24 and Hot from 25 up.

With the input 14, your script prints:

Temperature: 14
Cold

With 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics