Windows 7 / Getting Started

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

  1. Launch an instance of the PowerShell ISE.
  2. 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"
    Get-service | Select * | Where {$_.name -eq $Name }
    This will return the details on the Windows Defender service.
  3. 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 }
  4. 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
    
  5. 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"}
    }
  6. 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.
  7. 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
  8. 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.
  9. At this point you should save the script. Click the Save icon. Browse to C:\Scripts and save it as CheckService.ps1.
  10. Execute the script file using the bottom pane of the ISE by typing the following and pressing Enter:
    c:\scripts\CheckService.ps1
[Previous] [Contents] [Next]

In this tutorial:

  1. Working with the Command Prompt
  2. Starting and Ending a Command Prompt Session
  3. Easy ways to invoke administrator Command Prompt sessions
  4. Starting Command Prompt at a Particular Folder
  5. Strings with Spaces Need Quotes
  6. Cmd.exe vs. Command.com
  7. Commands Are Not Case Sensitive
  8. Starting Command Prompt and Running a Command
  9. Cmd.exe and Other Command Prompts
  10. Using AutoRun to Execute Commands When Command Prompt Starts
  11. Using Cmds Command-Line Syntax
  12. Using Commands
  13. Type /? for help
  14. Starting Programs
  15. Open Windows Explorer at the current Command Prompt folder
  16. Using File-Name and Folder-Name Completion
  17. Use a different completion character
  18. Using Wildcards
  19. Editing the Command Line
  20. Using Command Symbols
  21. The Redirection Symbols
  22. The Pipe Symbol
  23. The Command Combination Symbols
  24. Pausing or Canceling Commands
  25. Simplifying Command Entry with Doskey Macros
  26. DOSKEY Saves Typing
  27. System Variables Identify the Environment
  28. Viewing Environment Variables
  29. Modifying Environment Variables
  30. Predefined Environment Variables
  31. Customizing Command Prompt Windows
  32. Setting the Window Size and Position
  33. Setting the Window Size and Position Visually
  34. Selecting a Font
  35. Setting Colors
  36. Setting Other Options
  37. Copy and paste in the command prompt window
  38. Navigating from the command prompt
  39. Printing a list of filenames
  40. Commands Use Paths
  41. Identifying Executables
  42. Modifying the Path to Executables
  43. Modifying the Path with the GUI
  44. Changing the Current Path with CD
  45. Changing the Current Path with Windows Explorer
  46. Capturing the Output
  47. A Sampling of Commands
  48. Dir
  49. Copy
  50. XCopy
  51. SET
  52. NET USE
  53. SystemInfo
  54. DriverQuery
  55. Echo
  56. Advanced Shell Commands
  57. Creating a Batch File
  58. Scheduling a Batch File
  59. Creating Scheduled Tasks with a Script
  60. Using Windows PowerShell and the PowerShell ISE
  61. Windows PowerShell ISE
  62. PowerShell Commands
  63. Verbs and Nouns
  64. Sending Output to a Text File
  65. PowerShell Syntax
  66. Variables Created with a $ Symbol
  67. Comparison Operators
  68. Parentheses, Brackets, and Braces
  69. Running PowerShell Scripts
  70. PowerShell Execution Policy
  71. Changing the Execution Policy
  72. Looping
  73. Collections
  74. Creating a PowerShell Script
  75. Documenting Scripts
  76. Using PowerShell Commands
  77. Getting Help on PowerShell
  78. Using WMI_Cmdlets
  79. Getting Details on an Object
  80. Querying Information on Specific Objects
  81. Terminate Applications with Win32_process
  82. Formatting Output with the -f Format Operator
  83. Filtering the Output with the Where-Object Command
  84. Using the IF statement
  85. Using the Switch Statement
  86. Script Reusability