Switch Statement Usage in PowerShell

PowerShell: Switch Statement Usage

Usually, an if-else construct is used to test conditions in PowerShell scripts. If you need to immediately check several conditions instead of doing complex constructions with if-else, it is much easier to use the switch statement.

The syntax of the construction with the Switch operator is looks like follow:

Switch -options (value) { 
Pattern 1 {action1} 
Pattern 2 {action2} 
Pattern x {action3}
default { defaultaction}}

The Switch statement compares the value of each item in turn with each condition (pattern), and if it matches, it performs the action specified for this condition.

PowerShell: Switch operator

Let’s look on an example of a simple PowerShell script that checks the value of the var1 variable against one of the following values.

$var1 = 2
Switch ($var1) { 
1 {write-host ″Action one″} 
2 {write-host ″Action two″} 
3 {write-host ″Action three″} 

powershell switch statement

In this example, the value of the var1 variable matches the second condition, so the ″Action two″ is displayed.

In the example above, if the value of $var1 = 0, the Switch statement doesn’t perform any actions. You can create a default action that applies when none of the conditions are met. To do this, use the Default key.

$var1 = 0
Switch ($var1) { 
1 {write-host ″Action one″} 
2 {write-host ″Action two″} 
3 {write-host ″Action three″}
Default {″No action″; exit}

The Switch statement sequentially checks all conditions. If after a match with a condition you want to leave the Switch structure, use the Break operator.

For example:

1 {write-host ″Action one″;break}

You can check the value of a certain object using the Switch statement. For example, check the status of the DNS Client service using the cmdlet Get-Service, and if the service is stopped, we will start it. If the service is in the Stopping state, the script will restart it (let it be the default action).

switch (Get-Service | where {$_.name -eq 'Dnscache'})
{$_.status -eq 'Running'} {'DNS client service is running'}
{$_.status -eq 'Stopped'} {'DNS client service is stopped'; Start-Service Dnscache }
Default { Restart-Service Dnscache; {'DNS client service restarting' }; exit}

powershell switch

One of the most useful features of the switch statement is the built-in ability to work with regular expressions with the -regexp key.

For example, using a regular expression, you can verify that the following line begins or ends with a specific character:

switch -regex ("theitbros")
'^t' { "Begins with t" }
's$' { "ends with s" }
'^a' { "Begins with a" }
Begins with t
ends with s

powershell switch example

Also in the scripts, the following PowerShell switch statement parameters may be useful:

  • Wildcard — you can use wildcards in the expression (*,?, [asd]);
  • Exact — exact, case-insensitive comparison of the string;
  • CaseSensitive — the case sensitive check (if the condition is not a string, this parameter is ignored);
  • File — input data is taken from a file. For example:
switch -file c:\ps\test.txt
'cat' {write-host 'I found a cat'}
'dog' { write-host 'I found a dog'}
'bird'{ write-host 'I found a bird'}
Default {write-host ‘nothing found’}

You may also like:

How to transfer FSMO Roles From a Failed Domain Co... In case domain controller, which owns FSMO (Flexible Single Master Operation) roles, is fail (virus attack, fatal software problems or catastrophic ha...
Time Configuration for a Virtualized Domain Contro... Today we will talk about some of the features of time configuration on a virtualized domain controllers. Typically, the time synchronization scheme in...
Removing Old and Unused Drivers from Driver Store ... Each time you install or update your device driver, Windows OS (since Vista) continues to store the old version of the driver in the system Driver Sto...
Get-service: Checking the Status of Windows Servic... Using the Get-Service cmdlet you can get a list of all the services installed on the operating system, its status and startup type. This one and other...
How to Create a GUI for PowerShell Scripts? One of the significant drawbacks of PowerShell scripts, when used by users (not sysadmins or programmers), is its command-line interface. The result o...

Add Your Comment