PowerShell Switch Statement

Introduction to Windows PowerShell's Switch Statement

As with other scripting languages, PowerShell provides a variety of commands to perform branching logic.  For simple cases, with few options, the 'If' construction works well.  The difficult arises when 'If' becomes a victim of its own success and you have 5 or 6 options, for that situation it is more efficient to use PowerShell's 'Switch' command.

Topics for PowerShell's Switch Command

It is likely that your real-life task for Switch will be trickier than the following simple examples.  However, it is worth studying a range of basic examples to get a feel for the structure and the rhythm of the command.


The Basic Structure of PowerShell's Switch Statement

A curious feature of the construction is that the word 'Switch' introduces the input, and is then never seen again, all that you see thereafter is rows of patterns with their matching {Statement Blocks}.  Also observe that there is an extra pair of {braces} surrounding the whole pattern section.

Switch (pipeline) {
Pattern 1 {Statement block}
Pattern 2 {Statement block}
Pattern n {Statement block}

For simple examples, you could write the Switch command all on one line:

Switch (3) { 1{ "Red" } 2{ "Yellow" } 3{ "Green" } }

Result: Green.  PowerShell switches the input of 3 to an output of Green.  Incidentally, the equivalent of 'Switch' in VBScript is 'Select Case'.

Learning Points

Note 1: Trace the overall structure of the Switch command:
Switch (Value, or Pipeline in parenthesis) {Actions in braces}

Note 2: The "Block" for each Switch is enclosed not only by {braces}, but also by speech marks { "Yellow" }.

Note 3: Remember to pair the initial { brace, with a final matching brace, even if the whole structure spans multiple lines.}

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds' Network Performance Monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds' Network Performance Monitor

Case Study 1: Switch with WMI Disk

A difficulty occurred when we interrogated the computer's disks with WMI.  Specifically, the output reports DriveType as a number, whereas we want a meaningful name for the type of disk.  The extra step in this example was to research which drive type corresponded to which number, for example if $Drive.DeviceID returns a value of 3, that means the disk type is a "Hard drive".

Case Study 1 - Problem understanding the output

# Case Study 1 - Problem
$Disk = Get-WmiObject win32_logicaldisk
Foreach ($Drive in $Disk) {
$Drive.DeviceID + $Drive.DriveType

We want an answer to the question: 'What does the DriveType number mean?'  It would be useful if the script gave us a name rather than a number.  Research reveals that there are at least 5 possible disk types, therefore multiple 'If' statements would be cumbersome, 'Switch' is more elegant.

Case Study 1 - Solution use 'Switch'

Whenever I add a 'Switch' statement to my script, I think - 'good job'.  And I follow up by saying: 'Why don't I use the Switch construction more often?' 

# Case Study 1 - Solution with PowerShell 'Switch' Param
$Disk = Get-WmiObject win32_logicaldisk
Foreach ($Drive in $Disk) {Switch ($Drive.DriveType) {
1{ $Drive.DeviceID + " Unknown" }
2{ $Drive.DeviceID + " Floppy or Removable Drive" }
3{ $Drive.DeviceID + " Hard Drive" }
4{ $Drive.DeviceID + " Network Drive" }
5{ $Drive.DeviceID + " CD" }
6{ $Drive.DeviceID + " RAM Disk" }

Learning Points

Note 4:  Before examining the solution in Case Study 2, take the time to understand the underlying WmiObject construction in Case Study 1.  In particular observe the format:
Foreach (condition) {Block Command}.

Note 5: The case study solution builds on the first script by adding the Switch block.  To my way of thinking, there are two loops, the outer Foreach and an inner Switch loop.  Check what I mean by matching the last two {lonely} braces with their opening counterparts.


Challenge 1:  Just to get experience and control of the script try changing "Hard Drive" to "Fixed Disk"

Challenge 2: Create a mapped network drive, then run the script again.  Launch Windows Explorer then click on the Tools menu, this is the easiest way to map a local drive letter to a UNC share.

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft's operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try - it's free.

Download your free copy of WMI Monitor

Learning More About PowerShell's Switch Statement

For once PowerShell's help did not do what I wanted, Get-Help Switch did not work.  However, I discovered that the secret was to prefix switch with about_.  Try:

Get-Help about_switch

This help file introduced me to the -Wildcard statement, which helped with matching the input to the Switch clause.

Incidentally, PowerShell supports a whole family of about_ commands, for example you could try:
help about_Foreach.   See more about PowerShell's Help About_ family.

Switch Case Study 2 - Featuring Switch with -Wildcard

The objective of this 'Switch' example is to return a count for each type of error message in the Application eventlog.

# PowerShell Switch script to count eventlog messages
Function EventType{
$errors = 0
$warnings = 0
$info = 0
Process {
Switch -Wildcard ($_.entrytype) {
   "err*" {$errors++}
   "warn*" {$warnings++}
   "info*" {$info++}
    default {}
           }# End of switch block
       }# End of Process block
"The Application log contains " + $errors + " error messages."
"The Application log contains " + $warnings + " warning messages."
"The Application log contains " + $info + " information messages. `n"
          } # End block
} # End of function
Get-eventlog "application" -newest 250 | EventType

Note 6: Observe the -Wildcard switch with err*, info* and warn*.  To test the effect, try removing the -Wildcard statement.

Note 7: The layout above emphasises the branches, or the multiple 'Patterns', whose values get switched to their respective {Blocks}.

See more about PowerShell parameter functions ยป

Summary of PowerShell's 'Switch' Statement

The 'If' family are easy to use for scripts that require branching logic.  However, when the number of options exceeds about 5, then 'Switch' is easier to code and easier to add more options.  By trying a few simple examples you will soon appreciate the types of bracket, and the structure of the pattern with its matching statement block. 

I say again, 'Switch' is one of the most satisfying constructions to create, therefore never miss a chance to replace multiple 'If's with one 'Switch'.

If you like this page then please share it with your friends


See more Windows PowerShell flow control examples

PowerShell Switch Statement  • PowerShell Real-life Techniques  • Free Permissions Analyzer

Differences between For, ForEach and ForEach-Object  • PowerShell Loops  • PowerShell Home

Conditional Operators   • Do While Loop  • PowerShell If Statement  • PowerShell Brackets

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.



Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2017 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: