Subscribe to Windows IT Pro
November 21, 2008 12:00 AM

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
Windows IT Pro
InstantDoc ID #100411
Rating: (0)
Downloads
100411.zip

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

Related Content:

ARTICLE TOOLS

Comments
    There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement

advertisement

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.