Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  Advanced Search 


December 2008

Test for Numerous Conditions with PowerShell's switch Statement

Lesson 3 in the PowerShell 201 series explores how and when to use the switch statement and its components
RSS
Subscribe to Windows IT Pro | See More Systems Administration Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Download the Code Here

Executive Summary: Lesson 3 of Robert Sheldon's PowerShell 201 series discusses Microsoft Windows PowerShell's switch statement. The switch statement is easier to use than PowerShell's if statement when you need to test for numerous conditions and perform different actions based on those conditions. This lesson looks at the switch statement's components and demonstrates how to use them in the PowerShell console.

Windows PowerShell’s switch statement is a powerful language construct that lets you test for specific conditions, similar to an if statement. However, a switch statement is easier to implement when you want to evaluate numerous conditions. Let’s look at the various components that make up the switch statement and explore how to use them to automate such tasks as retrieving System event log entries and performing certain actions based on the type of entry, and moving and deleting files based on their filenames.

Creating Switch Statements
The switch statement compares one or more values to one or more conditions. For each condition that evaluates to true, the statement runs the script block associated with that condition. To better understand how a switch statement works, let’s take a look at its syntax:

switch <options> (<collection>)
{
  <condition 1> {<script block 1>}
  [<condition 2> {<script block 2>}]
  [<condition 3> {<script block 3>}]
  [<condition n> {<script block n>}]
  [default {<default script block>}]
}

The first line begins with the keyword switch, followed by one or more options and a collection. The switch statement supports five options that let you, for example, use wildcards and regular expressions. The collection, which is enclosed in parentheses, contains what you’re checking (e.g., events, files). It can consist of zero or more elements.

Windows It Pro Resources

To read the previous lessons in the PowerShell

201 series, go to “Iterating Through Collections with PowerShell’s foreach Loops,” InstantDoc ID 99873

“Controlling Your Code’s Flow with PowerShell’s Conditional Statements,” InstantDoc ID 100141

The braces in the second and last line enclose the switch statement’s script block. The first line in this block includes a condition and that condition’s script block, which is also enclosed in braces. If the condition evaluates to true, the condition’s script block runs. You can include as many condition/script block pairs as necessary. In addition, you can include an optional default clause that contains a script block, which runs only when none of the conditions evaluate to true.

Now let’s look at an example. The code in Listing 1 defines the $event variable and uses that variable in a switch statement. The first line uses the Get-EventLog cmdlet to retrieve the most recent event from the local computer’s System event log. When you use this cmdlet to retrieve System event log entries, it returns a Microsoft .NET Framework System.Diagnostics.EventLog- Entry object for each event. This object returns the information you typically find in a System event log entry, such as the when the event occurred, the type of event, and the event’s message.

In Listing 1, the Get-EventLog cmdlet assigns the information from the most recent event to the $event variable. Using the EventLogEntry object’s EntryType property, the switch statement retrieves the type of event and compares that element to the defined conditions.

In a switch statement, you can simply specify a value as a condition. PowerShell then automatically compares that value to each collection element. As callout A in Listing 1 shows, the first condition is defined as error. When this value is equal to the collection element (i.e., the EntryType property value), the condition evaluates to true and the script block runs. In other words, when the event type is error, the script block outputs the word ERROR: followed by the event’s message, which is obtained using the EventLogEntry object’s Message property.

The switch statement’s script block contains two other conditions, but you can define as many conditions as necessary. For each condition that evaluates to true, the associated script block runs. If multiple conditions evaluate to true, all associated script blocks run. In this example, only one condition script block will run because the collection contains only one element.

Note that, by default, the switch statement is case insensitive. For example, you can spell the first condition as error, ERROR, or Error, and the results will be the same. However, you can override this default behavior by specifying the -casesensitive option, as in

switch -casesensitive ($event.EntryType)

One other point I want to make concerns the collection. The code in Listing 1 retrieves the EntryType property value as part of the collection. However, you can retrieve that value in the conditions, as shown in Listing 2.

Notice that the collection now includes only $event. The conditions use the $_ builtin variable to reference the current $event value, then use the EntryType property to retrieve the entry type. When you take this approach, you must define the entire condition and enclose it in braces. For example, the condition {$_.entrytype -eq "error"} specifically says that the EntryType value must equal error. Listing 2 will return the same results as Listing 1.

When working with a collection that contains one element, you’ll probably want to stick with the first approach because it’s simpler. However, when a collection contains multiple elements, you have to use the second approach if the switch statement can’t work with the collection as is. For example, if you use Get-EventLog to return multiple system events, you must retrieve the EntryType value in each condition, as Listing 3 shows. In this code, the collection specifies only the variable name $events. This collection contains the last 10 system events. The conditions use the EntryType property to retrieve the entry type. Listing 3 returns results similar to those in Figure 1.

Continue to page 2

   Previous  [1]  2  Next 


Top Viewed ArticlesView all articles
No Jobs, No Excitement at Apple's Last Macworld Keynote

Apple CEO Steve Jobs made the right move in skipping out on his company's last appearance at Macworld: In a Tuesday keynote address at the conference, Apple had no interesting new products to sell, opting instead to spend mind-numbing amounts of time on ...

Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

Where is Microsoft NetMeeting in Windows XP?

...


Related Articles PowerShell 101, Lesson 6

PowerShell 101, Lesson 5

PowerShell 101, Lesson 4

PowerShell 101, Lesson 3

Windows OSs Whitepapers Why SaaS is the Right Solution for Log Management

Related Events Virtualization Forum: Optimizing Storage, Networks, Desktops, and Security

PowerShell 201 - eLearning Series with Paul Robichaux

Cloud Computing Forum: Integrating Software, Server and Storage as a Service into Your Enterprise IT Delivery Model

Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting Resources Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro Windows Dev Pro IT Job Hound ITTV
IT Library Technology Resource Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2009 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing