|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: