Introduction to Windows 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.
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 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}.
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 with 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.
Note 1: 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 2: 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.
Guy Recommends: SolarWinds LANSurveyor
LANSurveyor will produce a neat diagram of your network topology. But that's
just the start;
LANSurveyor can
create an inventory of the hardware and software
of your machines and network devices. Other neat features include dynamic
update for when you add new devices to your network. I also love the ability to export
the diagrams
to Microsoft Visio.
Finally, Guy bets that if you take a free trial of LANSurveyor then you will
find a device on your network that you had forgotten about, or someone else
installed without you realizing!
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.
When I wanted help about the switch command, at first PowerShell's help did not do what I wanted. The secret was
to add
the about_ prefix. Try:
help about_switch
What the about_switch help file reveals is that you could use wildcards
in the matching clause.
Incidentally, PowerShell supports a whole family of about_ commands, for example you
could try:
help about_foreach
Case Study 2 - Featuring Switch with -wildcard
Case Study 2 - Count the types of error message in the
Application eventlog
# PowerShell script to count eventlog messages function EventType{ BEGIN { $errors = 0 $warnings = 0 $info =
0 } PROCESS { switch -wildcard ($_.entrytype) { "err*"
{$errors++} "warn*" {$warnings++} "info*" {$info++} default {}
}#switch block }#process block END { "The Application log contains " +
$errors + " error messages." "The Application log contains " + $warnings + "
warning messages." "The Application log contains " + $info + " information
messages." }#end block }#function block get-eventlog "application"
-newest 250 | EventType
Note 1: Observe the -wildcard switch with err*, info*
and warn*. To test the effect, try removing the -wildcard parameter.
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'.
Please write in if you see errors of any kind. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
Guy
Recommends: Orion's NPM - Network Performance Monitor
Orion's performance monitor is designed for detecting network outages.
A network-centric
view make it easy to see what's working, and what needs your attention.
This utility guides you through troubleshooting by indicating whether the
root cause is faulty equipment or resource overload.