Using the Switch Statement
While the IF statement is useful when choosing between one or two options, when you start choosing between many options, it becomes very cumbersome with all of the IF ELSEIF ELSE clauses. A solution is the Switch statement, which is very valuable when you want to take one of many possible choices.
Note If you've done programming with other scripting or compiled languages, you may have run across the Case statement If you know the Case statement, you know the Switch statement-just by another name The Switch statement in PowerShell works just like the Case statement in other languages.
The Switch statement uses the value of a variable to determine which action to take. The basic syntax is
$switchVar Switch ($switchVar) { Value1 {"action for this value"} Value2 {"action for this value"} Value3 {"action for this value"} }
An example of the Switch statement using the PowerShell ISE. This example will show you how to determine the state of a service and then take different actions based on the state.
Using the Switch Statement
- Launch an instance of the PowerShell ISE.
- Enter the following command in the top pane, and press F5 to execute it. Note that
you can use the Tab key to save some typing, just as you can in PowerShell.
$Name = "WinDefend"
This will return the details on the Windows Defender service.
Get-service | Select * | Where {$_.name -eq $Name } - Now modify the command to populate the $svc variable with the results as a collection
by adding $svc = to the beginning of the command. It will look like this:
$svc = Get-service | Select * | Where {$_.name -eq $Name }
- Next, create a variable named $status and populate it with the status of Windows
Defender (which is stored in the $svc collection as $svc.status) with this line. If
desired, you can use the Write-host command to show you the status and execute
the entire script.
$status = $svc.status Write-Host $svc.Name "Service is" $status
- Next, create the Switch statement using the $Status variable.
Switch ($Status) { "Running" {Write-Host "Service is running"} "Stopped" {Write-Host "Service is stopped"} "Paused"{Write-Host "Service is paused"} }
- Execute the script. You may not want the first Write-Host line to execute, so you can "comment it out" by placing the # symbol at the beginning of the line. Why would you comment it out and not delete it? You may want to easily add it in later for debugging purposes, and it is easier to delete the # character than it is to type in the whole line again. Your display will look similar to the following graphic.
- Instead of just displaying the status, you may want to take an action. For example, if
it's stopped, you can start it by adding this line in the "Stopped" section:
Start-Service $Name
- You can also run only part of your script in the ISE. Use your mouse to highlight only
the following part of the first line in the top of the ISE:
Get-service | Select * | Where {$_.name -eq $Name
You can click the Run Selection icon (next to the Run Script icon) or press the F8 key to run only the highlighted text. - At this point you should save the script. Click the Save icon. Browse to C:\Scripts and save it as CheckService.ps1.
- Execute the script file using the bottom pane of the ISE by typing the following and
pressing Enter:
c:\scripts\CheckService.ps1
In this tutorial:
- Working with the Command Prompt
- Starting and Ending a Command Prompt Session
- Easy ways to invoke administrator Command Prompt sessions
- Starting Command Prompt at a Particular Folder
- Strings with Spaces Need Quotes
- Cmd.exe vs. Command.com
- Commands Are Not Case Sensitive
- Starting Command Prompt and Running a Command
- Cmd.exe and Other Command Prompts
- Using AutoRun to Execute Commands When Command Prompt Starts
- Using Cmds Command-Line Syntax
- Using Commands
- Type /? for help
- Starting Programs
- Open Windows Explorer at the current Command Prompt folder
- Using File-Name and Folder-Name Completion
- Use a different completion character
- Using Wildcards
- Editing the Command Line
- Using Command Symbols
- The Redirection Symbols
- The Pipe Symbol
- The Command Combination Symbols
- Pausing or Canceling Commands
- Simplifying Command Entry with Doskey Macros
- DOSKEY Saves Typing
- System Variables Identify the Environment
- Viewing Environment Variables
- Modifying Environment Variables
- Predefined Environment Variables
- Customizing Command Prompt Windows
- Setting the Window Size and Position
- Setting the Window Size and Position Visually
- Selecting a Font
- Setting Colors
- Setting Other Options
- Copy and paste in the command prompt window
- Navigating from the command prompt
- Printing a list of filenames
- Commands Use Paths
- Identifying Executables
- Modifying the Path to Executables
- Modifying the Path with the GUI
- Changing the Current Path with CD
- Changing the Current Path with Windows Explorer
- Capturing the Output
- A Sampling of Commands
- Dir
- Copy
- XCopy
- SET
- NET USE
- SystemInfo
- DriverQuery
- Echo
- Advanced Shell Commands
- Creating a Batch File
- Scheduling a Batch File
- Creating Scheduled Tasks with a Script
- Using Windows PowerShell and the PowerShell ISE
- Windows PowerShell ISE
- PowerShell Commands
- Verbs and Nouns
- Sending Output to a Text File
- PowerShell Syntax
- Variables Created with a $ Symbol
- Comparison Operators
- Parentheses, Brackets, and Braces
- Running PowerShell Scripts
- PowerShell Execution Policy
- Changing the Execution Policy
- Looping
- Collections
- Creating a PowerShell Script
- Documenting Scripts
- Using PowerShell Commands
- Getting Help on PowerShell
- Using WMI_Cmdlets
- Getting Details on an Object
- Querying Information on Specific Objects
- Terminate Applications with Win32_process
- Formatting Output with the -f Format Operator
- Filtering the Output with the Where-Object Command
- Using the IF statement
- Using the Switch Statement
- Script Reusability