PSMonday #32: December 5, 2016

Topic: Switch Statement II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

Okay, we’re back with more information on the Switch language construct. We’ll start where we left off: getting the Switch to act more like the If statement. In our first example we’ll do just that, and we do it with the break statement.

Switch (3) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'; break}
    4 {'Four'}
    3 {'Three (again)'}
}

Three

With the inclusion of the break statement, we exit the Switch construct the moment our condition is matched and action is completed.

Typically, I’ll include several break statements in my Switch statements. This is because once my condition is matched and the action completed, I’m typically ready to move past my Switch. In the below example, we’ll exit the Switch the moment a match is made and the action complete.

Switch (3) {
    1 {'One'; break}
    2 {'Two'; break}
    3 {'Three'; break}
    4 {'Four'}
}

Notice that I didn’t use a break statement on the last condition. It doesn’t make sense to include it. If we make it down to the last possible condition, I can be certain it’s not going to check anymore conditions, as there aren’t any more to check.

The switch statement can check collections, too. In this example, we evaluate the test-value of 4, and then the test-value of 2.

Switch (4,2) {
    1 {'One'}
    2 {'Two'}
    3 {'Three'}
    4 {'Four'}
    5 {'Five'}
}

Four
Two

It’s probably a good time to indicate that the break statement can break things, as well. It’s not always a good idea that it’s used. In this next example, 2 is never evaluated because we exit the Switch the moment the action for 4 is complete.

Switch (4,2) {
    1 {'One'; break}
    2 {'Two'; break}
    3 {'Three'; break}
    4 {'Four'; break}
    5 {'Five'}
}

Four

That’s it for today. We have at least one more PSMonday dedicated to the Switch. Maybe two. Okay, probably two.

Leave a Reply

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