Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

powershell

How to use the switch statement in PowerShell

Gutha Vamsi Krishna

Overview

The switch statement is used to switch between multiple conditions. It is similar to using multiple series of if statements. Using the switch statement in that situation is very convenient and readable.

Syntax

switch(value)
{
    //conditions
}

Parameters

It takes a value as a parameter to match the condition defined in the switch statement. We can also pass a list of values.

Let's take a look at an example of this.

Example

#!/usr/bin/pwsh -Command

switch (4)
{
    1 {"Condition one."}
    2 {"Condition two."}
    3 {"Condition three."}
    4 {"Condition four."}
    Default {
        "No matches"
    }
}
Example of the switch statement in PowerShell

Explanation

  • Line 3: We use a switch statement and pass 4 as a value to it.
  • Lines 4–12: We define different conditions in the switch statement. The switch statement checks each condition one by one. It executes the condition that matches the value that is passed to it. It executes the Default case if no condition matches the passed value.

RELATED TAGS

powershell
RELATED COURSES

View all Courses

Keep Exploring