EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial Switch Case in PowerShell
Secondary Sidebar
PowerShell Tutorial
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Switch Case in PowerShell

By Chirag NagarekarChirag Nagarekar

Switch Case in PowerShell

Introduction to Switch Case in PowerShell

Switch function in PowerShell is used to handle multiple If statements or in other terms it is replacement of multiple conditions If/Else If/Else. To check a single condition in Script or Function, you can use If/else statement but if you want to evaluate more IF statements then use Switch.

Switch is better compare to multiple If statements and easy to implement and simple use for coding. There are multiple conditions under each statement and when one of them satisfies then the action is performed.

 Syntax:

Switch (<Value>)
{
<Condition1> {Action1}
<Condition2> {Action2}
}

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,294 ratings)

Full Syntax:

Switch [-regex | -wildcard | -exact ] [ -casesensitive ]  ( <value> ) {
"String" | Number | Variable | { expression } {  statementlist  }
default { statementlist }
}

OR

Switch [-regex | -wildcard | -exact ] [ -casesensitive ]  -file  [filename]{
"String" | Number | Variable | { expression } {  statementlist  }
default { statementlist }
}

Parameters of Switch Case in PowerShell

  • Regex: It is also called Regular Expression. Performs the Regular expression check against the value of the condition. If you use Regex, WildCard and Exacts are ignored. Also, if the match clause is not a string then this parameter is ignored.
  • Wildcard: Indicates that the condition is a wildcard string. If you use Wildcard, Regex, and Exacts are ignored. Also, if the match clause is not a string then this parameter is ignored.
  • Exact: Performs the match against the exact string. If you use Exact, Wildcard and Regex are ignored and if the match clause is not a string then this parameter is ignored.
  • CaseSensitive: This parameter will check the condition that matches exactly with the passed Value (case sensitive) if it doesn’t match then this parameter is ignored. It also needs a string value.
  • File: Takes the file path as an input value rather than a string value. If multiple file parameters are passed, it takes only the last one. Each line of the file is read and evaluated against the condition and if the condition matches then it executes that value or displays a written message.

Flowchart

 Flowchart

How does Switch Works in PowerShell?

As shown in above the diagram, whenever any value (string, Integer, float or other data types), array, wildcards, files, etc. is passed then it starts matching conditions one by one and when condition matches, the script executes that block. For multiple matching values, multiple scrips block will be executed and if no matching value found and if default condition is specified then it executes that block otherwise there is null output.

Examples of Switch Case in PowerShell

Let us see the given example:

Example# 1

1. Simple switch function with string, integer value passed.

Code:

switch (3) {
1 {"One"}
2 {"Two"}
3 {"Three"}
}

Output:

powershell 1

Code:

switch("data"){
"abc"{"Abc executed"}
"xyz"{"Xyz Executed"}
"data"{"Data Executed"}
}

Output: 

powershell 2

Now, what if the parameter doesn’t match the expression. As an example given below, 5 doesn’t match with any of the Switch cases. In this case, the output will be null.

Code:

switch (5) {
1 {"One"}
2 {"Two"}
3 {"Three"}
}

To overcome the above problem, default needs to specify and default block executes when none of the parameter matches.

Code:

switch (5) {
1 {"One"}
2 {"Two"}
3 {"Three"}
default{"No Match Found"}
}

Output:

powershell 3

Example# 2

Let us see the given example:

Difference between if / else if /else and Switch. From the below example, you can understand how it is easy to write a script with the Switch function.

Code:

$time = 3
if($time -eq 1){"It's 1 O'Clock"}
elseif ($time -eq 2) {"It's 2 O'Clock"}
elseif ($time -eq 3) {"It's 3 O'Clock"}
else {"No Match Found"}

$time = 3
switch ($time) {
1 {"It's 1 O'Clock"}
2 {"It's 2 O'Clock"}
3 {"It's 3 O'Clock"}
default{"No Match found"}
}

Output: 

powershell 4

Execution time for both the methods.

Code:

$time = 3
Measure-Command {
if($time -eq 1){"It's 1 O'Clock"}
elseif ($time -eq 2) {"It's 2 O'Clock"}
elseif ($time -eq 3) {"It's 3 O'Clock"}
else {"No Match Found"}
}

TotalMilliseconds :

TotalMilliseconds

Code:

$time = 3
Measure-Command {
switch ($time) {
1 {"It's 1 O'Clock"}
2 {"It's 2 O'Clock"}
3 {"It's 3 O'Clock"}
default{"No Match found"}
}
}

TotalMilliseconds:

powershell21

Difference: 31.3154 milliseconds

This difference becomes vast when you write massive script or functions inside the switch.

1. Switch with Regex Parameter

If Regex is mentioned in switch, it evaluates the expression with passed value and if part of the condition matches then it executes that operation.

Consider the example below.

Code:

Switch ("Donkey"){
"Dog" {"Dog is Mentioned"}
"Cat" {"Cat is Mentioned"}
"Don" {"Donkey is Mentioned"}
"key" {"Donkey is mentioned again"}
default {"Nothing is mentioned"}
}

Output:

powershell 5

After adding Regex.

Code:

Switch -Regex ("Donkey"){
"Dog" {"Dog is Mentioned"}
"Cat" {"Cat is Mentioned"}
"Don" {"Donkey is Mentioned"}
"key" {"Donkey is mentioned again"}
default {"Nothing is mentioned"}
}

Output:

powershell 6

2. Switch with Wildcard Parameter

Wildcard works similar to Like parameter.

Code:

$msg = "Error, WMI connection failed"
Switch -Wildcard ($msg) {
"Error*" {"WMI Error"}
"Warning*" {"WMI Warning"}
"Successful*" {"WMI Connection Successful"}
}

Output: 

powershell 7PNG

3. Switch with Exact Parameter

Exact function is default in Switch. It doesn’t matter if you use it or not. But when you use two parameters at the same time then the last parameter takes precedence.

Code:

Switch -Regex -Exact ("Hello"){
"He" {"Hello World"}
"Hi" {"Hi World"}
Default {"No World"}
}

Output:

powershell 8PNG

Code:

Switch -Exact -Regex ("Hello"){
"He" {"Hello World"}
"Hi" {"Hi World"}
Default {"No World"}
}

Output:

powershell 9PNG

4. Switch with File Parameter

You can provide a file path directly to the Switch as a parameter. You can use File with a path to a file instead of giving it a variable expression.

Code:

Switch -Wildcard -File C:\temp\switchtest.txt {
"*Warning*"{Write-Warning $PSItem}
"*Error*"{Write-Error $PSItem}
}

Output:

switchcase in powershell. 2PNG

You can use $PSItem or $_ to work with current Items.

5. Switch with CaseSensitive parameter

When you use a Casesensitive parameter in a switch, then the condition has to match exactly by each character.

Code:

switch -CaseSensitive ("Hello") {
"HeLlo" {"This is different HeLlo"}
Default {"This is not Matching"}
}

Output: 

powershell 10PNG

6. Passing Array Value to switch function

Simple Array :

switch (10,12) {
9 { "Nine" }
10 { "Ten" }
11 {"Eleven"}
12 {"Twelve"}
Default {"None"}
}

Output:

passing array

Passing Array Object

Code:

$VMOps = @(
"VM_Delete"
"VM_Create"
)
switch ($VMops) {
"VM_Delete" {"VM Delete Operation"}
"VM_Create" {"VM Create Operation"}
"VM_Shutdown" {"VM Shutdown Operation"}
}

Output:

powershell 12PNG

7. Break condition

When you specify break condition, then Operation breaks in that loop and can’t continue further execution. This is pretty helpful when you don’t want to check further steps when condition satisfies and execution time becomes faster.

Code:

$VMOps = @(
"VM_Delete"
"VM_Create"
)
switch ($VMops) {
"VM_Delete" {
"VM Delete Operation"
break }
"VM_Create" {
"VM Create Operation"
break}
"VM_Shutdown" {
"VM Shutdown Operation"
break
}
}

Output:

breakcondition

If you notice, there is only one block executed and then it exits from the switch function.

8. Continue Condition

Continue parameter is used to skip the particular iteration. For example, if there are 3 items to match then it will execute first and when condition matches then it will skip other steps and move to the next step.

Code:

switch ('Hello') {
"hello" {'First Block Executes'
continue}
'HELLO' {'Second Block Executes'
continue }
'HeLLo'  {'Third Block Exectues'
continue }
Default {'Nothing executed'}
}

Output:

continue condition

As you can see there is only one argument passed (‘Hello’), it executes the first block only because the expression is matching and there is no other argument left to execute, the script will end.

  • One more mixed example of break and continue with Switch.

Code:

switch ('Alpha','Beta','Delta') {
"Alpha" {'First Block Executes'
continue}
'Beta' {'Second Block Executes'
break }
'Delta'  {'This will not Execute'}
}

Output:

powershell 15PNG

Conclusion

All in all, Switch is far better than implementing multiple If conditions and provides more functionality and reduction in execution time.

Recommended Articles

This has been a guide to Switch Case in PowerShell. Here we also discuss the syntax, parameters, and examples of switch case in Powershell. You may also have a look at the following articles to learn more-

  1. What is Shell Scripting?
  2. PowerShell Commands
  3. PowerShell Operators
  4. Uses Of Powershell
  5. Guide to Array in PowerShell with Examples
  6. Examples of Regex in PowerShell
  7. Complete Guide to Function in Shell Scripting
  8. Learn the Echo in Shell Scripting
  9. Examples of Switch Case in Shell Scripting
  10. Python Switch Case | How to Implement?
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
3 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more