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?

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

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

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.

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, and holds a number of certifications, including those relating to 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

Your email address will not be published. Required fields are marked *

*