PowerShell Genie

PowerShell if / elseif / else

if runs a block when a condition is true, elseif tests another condition, else catches everything remaining. The condition goes in parentheses and the block in braces.

Lesson 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Overview

What counts as true is worth knowing precisely, because PowerShell coerces values to boolean. Zero is false and any other number is true. An empty string is false, a non-empty one is true. $null is false. An empty array is false, and an array with one element takes the truthiness of that element. This means if ($result) is a reasonable way to ask whether a command returned anything.

Braces are not optional, even for a single statement. There is no one-line form without them.

For assigning one of two values, the ternary operator in PowerShell 7 is more compact: $status = $ok ? 'Pass' : 'Fail'. It does not exist in 5.1, so avoid it in scripts that must run there.

Inspect this example’s structure

Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

$score = 72 if ($score -ge 50) { 'Pass' } else { 'Try again' }
  1. Stage 1$scorePositional values or no named parameters

    An example to inspect

    Preview the example. Sign in for the full lesson and activities.

    $score = 72
    if ($score -ge 50) { 'Pass' } else { 'Try again' }

    What happens

    $score holds 72, and the condition asks whether it is at least 50. It is, so the string Pass is the result of the whole statement. Because the if statement produces a value, you can assign the result directly: $grade = if ($score -ge 50) { 'Pass' } else { 'Fail' }.

    Worth remembering

    • Condition in parentheses, body in braces. Braces are required.
    • 0, '', $null and empty arrays are all false.
    • if produces a value, so you can assign its result.
    • The ternary operator ? : is PowerShell 7 only.

    Primary documentation

    PowerShell objects and pipelines documentation

    Try it

    Illustrative output · values vary by environment

    1PS> $score = 72
    2PS> if ($score -ge 50) { 'Pass' } else { 'Try again' }

    Example reader

    Inspect this page's example

    Fictional browser data when supported

    Run supported commands against the practice data, or inspect the example without executing it.

    Ready to inspect.

      Tests a numeric condition and returns one of two strings.

      Show reference output

      Illustrative output · values vary by environment

      Pass

      Keep going

      Next: PowerShell switch
      Genie guidePowerShell if / elseif / else

      if runs a block when a condition is true, elseif tests another condition, else catches everything remaining. The condition goes in parentheses and the block in braces.