PowerShell: Too Many If Elses? Use Switch.

One of my favorite things in PowerShell (and other languages) is the switch statement. It’s clean and a much better alternative to a ton of if elses. Ever had this happen?

if ($state -eq -1)
{
    $diskstate = "Unknown"
}
elseif ($state -eq 0)
{
    $diskstate = "Inherited"
}
elseif ($state -eq 1)
{
    $diskstate = "Initializing"
}
elseif ($state -eq 2)
{
    $diskstate = "Online"
}

The better way to do it is by using the switch command.

switch ($state)
    {
        -1 { $diskstate = "Unknown" }
        0   { $diskstate = "Inherited" }
        1   { $diskstate = "Initializing" }
        2   { $diskstate = "Online" }
        3   { $diskstate = "Offline" }
        4   { $diskstate = "Failed" }
        128 { $diskstate = "Pending" }
        129 { $diskstate = "Online Pending" }
        130 { $diskstate = "Offline Pending" }
        default { $diskstate = "Unknown" }
    }

Just look how pretty that is. It gets better, though! My buddy Klaas Vandenberghe showed me a more succinct way to use switch.

$diskstate = switch ($state)
    {
        -1 { "Unknown" }
        0   { "Inherited" }
        1   { "Initializing" }
        2   { "Online" }
        3   { "Offline" }
        4   { "Failed" }
        128 { "Pending" }
        129 { "Online Pending" }
        130 { "Offline Pending" }
        default { "Unknown" }
    }

Even less code and makes total sense. Awesome. There’s even more to switch — the evaluations can get full on complex, so long as the evaluation ultimately equals $true. Take this example from sevecek. Well, his example with Klaas’ enhancement.

$optionSelected = Read-Host 'Do you want to mount the VHD image? (Yes/No/Y/N/0/1/True/False/T/F, default = No)'

$boolOption = switch ($optionSelected) {

  { 'Yes', 'Y', '1', 'True', 'T' -contains $_ } { "Yep!" }
  { 'No', 'N', '0', 'False', 'F' -contains $_ } { "Nope!" }
  default { 'another option' }
}

echo "You selected: $boolOption"

If you weren’t familiar with switch, I hope this was helpful. I know I was excited about its elegance when I was first introduced by Lee Holmes and Klaas’ enhancement made it even better.

Chrissy is a Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, holds a master's degree in Systems Engineering and is coauthor of Learn dbatools in a Month of Lunches. Chrissy is certified in SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

Posted in PowerShell
One comment on “PowerShell: Too Many If Elses? Use Switch.
  1. Bob Roudebush says:

    Mind = Blown! That’s some good stuff right there.

Leave a Reply