EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Switch Statement
Secondary Sidebar
PowerShell Tutorial
  • 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
  • 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
  • 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

PowerShell Switch Statement

By Priya PedamkarPriya Pedamkar

PowerShell Switch Statement

Introduction to PowerShell Switch Statement

A switch statement in PowerShell is the same as that of the switch in other programming languages.  The switch statement is used to evaluate a predefined list of conditions, in other words, it is equivalent to multiple if statements. The switch statement has a sequence of the condition and each condition has its own action to be performed. Whenever a condition is matched, its corresponding action is performed. Each condition inside a switch statement is considered as a case and the value for which switch statement is performed is checked for each case. This article will cover in detail the switch case statement. There is a default block to handle values that don’t match any cases.

Syntax

The basic syntax/structure of the switch statement is follows

switch(<valueToBeChecked>) {
<condition> {<actionToBePerformed>}
break;
<condition> {< actionToBePerformed >}
break;
<condition> {< actionToBePerformed >}
break;
Default {< actionToBePerformed >}
}

Code:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

switch (Jan)
{
Jan  {"It is Jan."}
Feb  {"It is Feb."}
Mar  {"It is Mar."}
Apr  {"It is Apr."}
}

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,171 ratings)

The above will produce an output of “It is Jan”.

Syntax #1

The other detailed syntax of the switch statement is as follows

switch [-regex|-wildcard|-exact][-casesensitive] (<value>)
{
"string"|number|variable|{ expression } { statementlist }
default { statementlist }
}

Syntax #2

switch [-regex|-wildcard|-exact][-casesensitive] -file filename
{
"string"|number|variable|{ expression } { statementlist }
default { statementlist }
}

Flow Diagram of PowerShell Switch Statement

Below is the flow diagram:

flow diagram

Key things about Switch Statement:

  • Either an object or an array of objects can be used as the switch variable.
  • There can be any number of case statements within a switch. Default and action blocks are optional.
  • The switch variable and the case variable must be of the same data type. It should either be a constant or a literal.
  • Whenever a case is matched, the statements following that are executed until a break statement is encountered.
  • When a break statement is encountered, the switch statement terminates. The control is shifted to the next statement following the break.
  • It is not necessary for each case to have a break if there is no break the subsequent statement is executed until a break is encountered.

Parameters

The following are the parameters of the switch.

  • Wildcard: This denotes that the condition being checked is a wildcard string. If the matching clause is not of string type, then the corresponding parameter is not considered. It is case insensitive comparison.
  • Exact: It denotes that an exact match must be there.  If the matching clause is not of string type, then the corresponding parameter is not considered. It is case insensitive.
  • Case Sensitive: It denotes a case sensitive match. If the matching clause is not of string type, then the corresponding parameter is not considered.
  • File: Input is taken from a file. In the case of multiple files specified, only the last file is used for comparison. Each line is evaluated by the switch statement. It is case insensitive.
  • Regex: It denotes regular expression must be considered for matching. If the matching clause is not of string type, then the corresponding parameter is not considered.

Examples to Implement PowerShell Switch Statement

Below are the examples are mentioned:

Examples #1

Code:

Write-Host "Demo of switch statement in PowerShell"
$name="vignesh"
switch($name)
{
"ram" {"my name is ram";break}
"raman" {"my name is raman";break}
"ramu" {"my name is ramu";break}
"Vignesh" {"my name is Vignesh";break}
"ram123" {"my name is ram123";break}
"ram45" {"my name is ram454";break}
"ramfdgdf" {"my name is ramdfgfdg";break}
"ramfgdf" {"my name is ramdgfdg";break}
"ramfgdfg" {"my name is ramdgg";break}
}
Write-Host "Demo with default block"
$city="NewYork"
switch($city)
{
"Tn" {"city name is TN";break}
"as" {"city name is as";break}
"sd" {"city name is sd";break}
"gf" {"city name is gf";break}
"gujarat" {"city name is gujarat";break}
"wqe" {"city name is wqe";break}
"ewrewr" {"city name is ewrewr";break}
"wer" {"city name is wer";break}
"ewr" {"city name is ewr";break}
default {"city is not present in the list";break}
}

Output:

PowerShell Switch Statement - 2

Examples #2

Code:

Write-Host "Demo of switch statement with array as input in PowerShell"
$name="vignesh"
$name1="Krishnakumar"
$name2="Nandhini"
$name3="Vyapini"
switch($name,$name1,$name2,$name3)
{
"Krishnakumar" {"my name is Krishnakumar";break}
"Nandhini" {"my name is Nandhini";break}
"ramu" {"my name is ramu";break}
"Vignesh" {"my name is Vignesh";break}
"ram123" {"my name is ram123";break}
"ram45" {"my name is ram454";break}
"ramfdgdf" {"my name is ramdfgfdg";break}
"ramfgdf" {"my name is ramdgfdg";break}
"Vyapini" {"my name is Vyapini";break}
}
Write-Host "Demo with default block"
$city="NewYork"
$city1="Tn"
$city2="gujarat"
$city3="Texas"
$city4="albama"
switch($city,$city1,$city2,$city3,$city4)
{
"Tn" {"city name is TN"}
"as" {"city name is as"}
"sd" {"city name is sd"}
"gf" {"city name is gf"}
"gujarat" {"city name is gujarat"}
"Texas" {"city name is texas"}
"ewrewr" {"city name is ewrewr";}
"wer" {"city name is wer"}
"NewYork" {"city name is NewYork"}
default {"city is not present in the list";break}
}

Output:

PowerShell Switch Statement - 3

Explanation: In the above example, if you look closely, in the first switch statement only the first match is printed. This is because as soon as a match is found, the corresponding break statement is executed, and the switch case is exited. In the second switch case, all the matching values are found because there is no break statement written for each case.

Examples #3

Code:

write-host "Demo of execution with and without break statement"
Write-Host "Demo of execution without break statement" -ForegroundColor Yellow
$Pm="Modi"
switch($pm)
{
"Modi" {"PM is Modi"}
"Indira gandhi" {"PM was Indira gandhi"}
"vallu" {"PM was Indira gandhi"}
"test" {"PM was Indira test"}
default {"none"}
"Modi" {"execution is done even after first match"}
}
Write-Host "Execution of switch with break statement" -ForegroundColor Yellow
switch($pm)
{
"Modi" {"PM is Modi";break}
"Indira gandhi" {"PM was Indira gandhi;break"}
"vallu" {"PM was Indira gandhi;break"}
"test" {"PM was Indira test;break"}
default {"none;break"}
"Modi" {"execution is done even after first match;break"}
}

Output:

execution is done

Explanation: In the above output, the same switch case is used with the same input parameter except that the first switch case doesn’t have a break statement. As you can see from above, if the break is not used execution is continued even after a successful match which doesn’t happen when a break is used.

Conclusion

Thus, the article covered in detail the switch case statement in PowerShell. It also explained with appropriate examples on the execution of a switch case statement and its syntax. The best way to learn more about this would be to try other various methods and practice them in sample scripts.

Recommended Articles

This is a guide to PowerShell Switch Statement. Here we discuss syntax, flow diagram to switch Statement and example to implement with proper codes and outputs. You can also go through our other related articles to learn more –

  1. PowerShell Convert String to Date
  2. PowerShell Get-Process
  3. Types of PowerShell Wildcards
  4. PowerShell If-Not | Examples
  5. Guide to Examples of PowerShell Rename Folder
  6. PowerShell Send Mail | Examples
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ 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
0 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