Ezine 153 PowerShell’s Switch

Ezine 153 – PowerShell’s Switch

VBScript has its ‘Case Select’, PowerShell has ‘Switch’.  The idea is to turn a meaningless number or phrase into a more useful output.  Actually, you could do much more than change the ‘Label’, you can execute an entire script block.

Topics for PowerShell’s Switch Command


This Week’s Secret

Bill Gates of all people, once said: ‘Your most unhappy customers are your greatest source of learning’.  What I find is that my HAPPY customers are also a goldmine of sage advice.  It was my readers who said: ‘Guy the ebooks are OK, but we want PDFs’.  Last week other readers say, actually, we still love the ebooks.  Typical customers!  They want BOTH an ebook and a PDF, so this is what I have created and made available free but only to ezine subscribers.

Just as I was about to publish these ezine, 3 readers wrote in with corrections to the initial PDF, not only do I want to thank them, but also I want to say that whenever a reader takes the trouble to write in, they are always right and Guy is always wrong.  Strange but true.

My PowerShell ebook is really 3 ebooks in one: 1) Getting Started, 2) Real-life Tasks and 3) Examples of PowerShell’s Syntax.  As a consequence it’s more difficult to proof read and to manage.  What I discovered was that I had covered out-File twice,  so I have amended the ebook / PDF to include a section on the ‘Switch’ command.  To draw attention to the main difference between the PDF I issued a fortnight ago and today’s free offering, I am featuring ‘Switch’ in this week’s ezine.

This Week’s Mission – Master PowerShell’s Switch Command

Whenever I add a ‘Switch’ clause to my script, I think – ‘good job’.  And I follow up by saying: ‘Why don’t I use the Switch construction more often?’  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.  Incidentally, the equivalent of ‘Switch’ in VBScript is ‘Select Case’.

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.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

The Basic Structure of PowerShell’s Switch Command

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

The layout below emphasises the branches, or the multiple ‘Patterns’ whose values get switched to their respective {Blocks}.

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 3 for Green.

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: The Free IP Address Tracker (IPAT) IP Tracker

Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets.  IPAT cracks this problem of allocating IP addresses in networks in two ways:

For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges. 

For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers. Download the Free IP Address Tracker

Case Study – 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
$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 ‘ifs’ would be cumbersome, Switch is more elegant.

# Case Study – 2 Solution
$Disk = get-WmiObject win32_logicaldisk
foreach ($Drive in $Disk) {switch ($Drive.DriveType) {
1{ $Drive.DeviceID + " Unknown" }
2{ $Drive.DeviceID + " Floppy" }
3{ $Drive.DeviceID + " Hard Drive" }
4{ $Drive.DeviceID + " Network Drive" }
5{ $Drive.DeviceID + " CD" }
6{ $Drive.DeviceID + " RAM Disk" }

Learning Points

Note 1:  Before examining the solution, study the first problem script which demonstrates the WmiObject construction.  In particular study the foreach (condition) {Block Command}.

Note 2: The case study solution builds on the problem 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.

Learning more about PowerShell’s Switch command

For once PowerShell’s help did not do what I wanted.  The secret was the about_ prefix.  Try:
help about_switch

PowerShell supports a whole family of about_ commands, for example you could try
help about_foreach

More about PowerShell’s Switch command

Summary of PowerShell’s ‘Switch’ command

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 Continue Statement  • PowerShell If Statement  • PowerShell ElseIf  • PowerShell Else

PowerShell Comparison Operators  • PowerShell If -And  • PowerShell If -Or   • PowerShell If -Not

Conditional Operators  • Where Filter  • PowerShell Real-life Techniques  • PowerShell Home

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.