Using the Switch Statement in PowerShell

An important form of selection in programming is the switch selection or switch statement. Using if/else and embedded if/else statements within each other can only work a majority of the time in logic, not 100%. In this tutorial you will learn how to use the switch statement in a PowerShell script.

Setup

If you have not already done so, click open Windows PowerShell ISE. Remember, you must always run Windows PowerShell as the Administrator for best results and unlimited access.

Step one.

The concept behind a switch statement is simple. Depending on user choice or choice automated by another sequence of logic, will determine your outcome from a listed of, choices. In the case that one choice is selected that choice can have any form of output or function within its switch case. You implement the code like a hierarchy, you put in the choice as a parameter, you switch "on" that particular case and whatever is in that case or "selection", would determine the output or function.

Step two.

Implementing a switch is easy. Copy and paste the following code into PowerShell ISE in the script pane and run it.

Example

$size = "S"
switch ($size)
{                
"S"          {Write-Host        "Small"}                
"M"        {Write-Host        "Medium"}                
"L"          {Write-Host        "Large"}                
"XL"       {Write-Host        "Extra Large"}                
"XXL"     {Write-Host        "Extra-Extra Large"}                
Default {Write-Host "Unknown Size"}
}
    

Copy and Try it

This code is functionally equivalent to an if-else selection logic, however it appears much cleaner. If you want to make extra selections, no problem, you won't have to search through the embedded if-else statements and add more values that $size can match and put whatever code whether it be a function or particular output statement and you are all set!

Remarks last but not least…

Thus we have the switch statement in PowerShell, not entirely horrible hopefully. Remember that switch statements are functionally equivalent to if-else statement structures. If you'd like to switch them all up, we don't blame you! Join us next time for more Windows PowerShell tutorials