Topic: If, If-Else, If-ElseIf
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.
Time to start learning, or reviewing, those language constructs — those “language commands,” as is the term used in the If statement’s, about topic help file. This file can be read by using the below command.
Get-Help -Name about_If
The If statement is typically the introductory control structure that someone encounters when they begin with a programming, or scripting, language. It is also the one people likely think of first when they need to start checking conditions and taking appropriate actions.
Here’s the basic, PowerShell If structure. We check a condition, and if it’s true, then we take the included action, or actions.
If (<condition>) { <action> }
There are several variations of the If statement: Here’s the If-Else. This is much like the If, except that if the condition results in false, it would complete action2 instead of exiting the construct and ultimately doing nothing. Had the condition been true, it would’ve completed action1, as we saw in the first example.
If (<condition>) { <action> } Else { <action2> }
Here’s the If-ElseIf. The way this works is if condition1 is false, it will try condition2. If that’s true, it’ll run action2, but if it’s false, it’ll exit and take no action.
If (<condition1>) { <action1> } ElseIf (<condition2>) { <action2> }
If-ElseIf-Else is just like the above example; however, if condition2 resulted in false, it would complete action3 as the default action.
If (<condition1>) { <action1> } ElseIf (<condition2>) { <action2> } Else { <action3> }
There’s really no limit to how many ElseIfs you include. Just keep in mind that Else completes a default action, as there’s no condition to check, while ElseIf requires a condition be checked (and be true), before the listed action is completed.
On a final note, if you’re going past three levels in your If constructs, then you may want to use the Switch statement. We’ll get to that one once we’ve completely knocked out the If.