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?

 1if ($state -eq -1)
 2{
 3    $diskstate = "Unknown"
 4}
 5elseif ($state -eq 0)
 6{
 7    $diskstate = "Inherited"
 8}
 9elseif ($state -eq 1)
10{
11    $diskstate = "Initializing"
12}
13elseif ($state -eq 2)
14{
15    $diskstate = "Online"
16}

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

 1switch ($state)
 2    {
 3        -1 { $diskstate = "Unknown" }
 4        0   { $diskstate = "Inherited" }
 5        1   { $diskstate = "Initializing" }
 6        2   { $diskstate = "Online" }
 7        3   { $diskstate = "Offline" }
 8        4   { $diskstate = "Failed" }
 9        128 { $diskstate = "Pending" }
10        129 { $diskstate = "Online Pending" }
11        130 { $diskstate = "Offline Pending" }
12        default { $diskstate = "Unknown" }
13    }

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

 1$diskstate = switch ($state)
 2    {
 3        -1 { "Unknown" }
 4        0   { "Inherited" }
 5        1   { "Initializing" }
 6        2   { "Online" }
 7        3   { "Offline" }
 8        4   { "Failed" }
 9        128 { "Pending" }
10        129 { "Online Pending" }
11        130 { "Offline Pending" }
12        default { "Unknown" }
13    }

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.

 1$optionSelected = Read-Host 'Do you want to mount the VHD image? (Yes/No/Y/N/0/1/True/False/T/F, default = No)'
 2
 3$boolOption = switch ($optionSelected) {
 4
 5  { 'Yes', 'Y', '1', 'True', 'T' -contains $\_ } { "Yep!" }
 6  { 'No', 'N', '0', 'False', 'F' -contains $\_ } { "Nope!" }
 7  default { 'another option' }
 8}
 9
10echo "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.