PowerShell for the DBA - If Else and Switch statements
As with most languages, there is the ability to use if else statements. In this article we will look at how to use if/else statements along with how to use the switch statement in PowerShell.
In this tutorial, we will learn how to declare, and use if/else and switch statements in PowerShell, along with several examples for a clear understanding.
- A very basic knowledge of coding in any other programming language will be assumed.
- No interaction with SQL Server will be covered in this article, that will be covered in a separate article.
Important note: I will be presenting all the examples using Windows PowerShell, but that shouldn't be a showstopper for you to follow along in any other OS of your choosing.
PowerShell If-Else Statement Examples
Below we will take a look at several different examples.
PowerShell If-Else statements in general in
If/else statements are conditional blocks that allow you to execute a specific set of code if a certain condition (or several conditions) is (are) met. This allows you to print a logical flow to whatever piece of software you are designing to solve a particular problem.
You can nest blocks of if/else statements, depending on your particular use case, so we will be checking how to do it in PowerShell.
There are a few combinations of these conditional blocks that we can use, so let's check them out:
PowerShell If statement on its own
You can simply use an if conditional block (or several one after the other) to evaluate a condition and execute a set of actions, without requiring an else block. Here is an example code block:
The syntax is pretty straightforward as you can see, it's just three different if statements without an else block. However, I want to point out something peculiar about PowerShell that's a bit different than most programming/scripting languages, and it's the comparison operators that it uses to evaluate conditions.
In this example, you don't see the classic "variable == 10" or "variable > 10" or "variable < 10", and it's because in PowerShell you don't make comparisons that way, you do it just like in the screenshot above.
Here is a list of comparison operators that you can find in PowerShell. Source - Microsoft's official documentation.
|greater than or equal
|less than or equal
|string matches wildcard pattern
|string does not match wildcard pattern
|string matches regex pattern
|string does not match regex pattern
|replaces strings matching a regex pattern
|collection contains a value
|collection does not contain a value
|value is in a collection
|value is not in a collection
|both objects are the same type
|the objects are not the same type
Now, after seeing this list you might also be wondering "how can I compare one condition and/or the other"? Good question, and here's the list of logical operators that you can use, followed by another example. Source - Microsoft's official documentation.
|Logical AND. TRUE when both
|(1 -eq 1) -and (1 -eq 2)
|statements are TRUE.
|Logical OR. TRUE when either
|(1 -eq 1) -or (1 -eq 2)
|statement is TRUE.
|Logical EXCLUSIVE OR. TRUE when
|(1 -eq 1) -xor (2 -eq 2)
|only one statement is TRUE
|Logical not. Negates the statement
|-not (1 -eq 1)
|Same as -not
|!(1 -eq 1)
One final detail to wrap up this example: the operators (as we saw with variables in the previous article, and as you can see in the screenshot) are not case sensitive, so -AND will work exactly the same as -and, and the same applies for the rest of the comparison and logical operators.
PowerShell If statement with an Else block
If your logic requires the introduction of an else block, here's a PowerShell script example of how you can use it:
Pretty straightforward, just specify the else block right after the if and you're good to go.
Nested PowerShell If-Else Statements
So far we covered the basics, but what if your logic requires an extra layer of complexity and you require several layers of if/else blocks to model a specific flow? Let's take a look at a few examples:
The purpose of these examples is to show the following:
- To nest if/else statements you must use the keyword elseif, which must have a condition specified (unlike a flat else block which directly contains the code to execute).
- You can have as many elseif blocks as you like.
- Within an elseif block you can have additional if/else blocks.
- If you write your if/else block in a single line, then PowerShell won't bark at you (unlike languages like Python that do require a particular indentation).
Up to this point, you're covered enough to use if/else statements inside a script of your own. With that said, let's now shift our attention to a structure that can be functionally equivalent to an if/else condition, the switch statement.
PowerShell If-Else Statements compared to Switch Statements
Switch statements are just like if/else statements, conditional blocks that allow you to specify a logic in your script, based on a condition (or a set of them). The difference between them is that the switch (at its basic level) evaluates a variable against a set of possible values, although in PowerShell the switch statement is beefed up (trust me, you'll see).
Since both if/else and switch statements are used for the same purpose at the basic level, you can go with whatever you feel more comfortable with. However, with the switch, you can end up with more elegant/readable code (which is definitely a plus), like the following example:
As you can see, both solutions deliver the exact same result, but the switch takes all the elegance/readability points straight to the bank.
PowerShell Switch Statements
As I mentioned before, the switch statement is beefed up in PowerShell because it can be used in different ways to accomplish different things, as opposed to the kind of "dry style" of the if/else block. Let's take a look at a few examples to see it in action:
Using the default keyword for switch in PowerShell
You use the default keyword when you want to do something if none of the above options made a match. In this particular example, you could also omit the use of the default keyword, but you would have to make sure that the initial value assigned to the $day variable that stores a desired value, providing the exact same effect.
Using the break statement for PowerShell Switch
This keyword is used to break the execution of the entire switch statement when a certain condition is met, preventing a waste of time/resources in continuing with the evaluation of the rest of the conditions if there's no point in doing so. Let's take a look at a couple of examples to understand this better:
Using the exact same example of the days of the week, I've slightly introduced a tiny change: I'm setting the $dayOfWeek variable to 1 and in the possible values within the switch, I've specified 1 for Sunday and Monday on purpose. As you can see, the output of the variable $day is "Monday" because it was the last option that made a match, but let's see what happens when we introduce the break keyword:
Note the result is different because when the match was made and the break was encountered, the rest of the options weren't evaluated anymore, so make sure to write efficient code when using this structure.
Storing the output in a variable for PowerShell Switch
Speaking of efficient and elegant code, let's take a look at a fancier way to store the output of a switch statement:
The efficiency part comes in the form of the breaks within each block to make it stop as soon as a match was made, and the elegant part comes in the form of the removal of the assigning of the value to the $day variable within each block. Therefore, by assigning the value in this way, you achieve the same end result in a fancier way.
Using wildcards to perform comparisons for PowerShell Switch
Yes, you read right, wildcards. In PowerShell you can perform comparisons using wildcard expressions, pretty handy right. Let's take a look at some examples so you can get a good idea how to use wildcards:
As you can see, there are different ways to achieve different results, based on how you use the different wildcards, pretty cool I'd say. Just be careful to specify the keyword -wildcard if you plan to use wildcards, otherwise it won't work even if you are trying to do comparisons using them.
Comparing multiple items per block for PowerShell Switch
There might be very specific cases where you need to compare multiple items per block, so you can achieve it like this:
Using regular expressions (regex) for comparisons with PowerShell Switch
PowerShell allows you to perform comparisons using regular expressions. I'm not going to take a deep dive into what regular expressions are nor how to master them, but still I need to fulfill my duty to present you at least an example of how you can use them within a switch statement, so let's have a quick look:
As with the use of wildcards, the usage or regular expressions won't work if you don't specify the keyword -regex, so make sure to keep that in mind.
Using the -file keyword to parse the content of a file for PowerShell Switch
See, I wasn't joking when I mentioned that the Switch statement in PowerShell was beefed up. This is by far one of the coolest things I've seen implemented in a programming/scripting language, for a "simple" switch statement. You can use the -file keyword to pass the path of a file and evaluate it against certain conditions to perform a set of actions. Pure awesomeness, so let's take a look at it:
Here's the contents of my file "C:\loveLetter.txt"
Here's how the switch statement is used:
As with wildcards and regular expressions, if you omit the -file keyword it won't work. Additionally, make sure that the file exists, that it is a text file, and that the path is a valid one. I would guess that if you are trying to parse a very large file, then your chances at succeeding will be bounded by the resources available within your computing device.
With this, I'd like to wrap up this article. Even though we only covered if/else and switch statements, you were able to see how versatile PowerShell is.
- In case you missed it, check out the previous article PowerShell for the SQL Server DBA - Variable Fundamentals.
- Now that you learned these two statements to control certain logical flows for your scripts, make sure to make your life easier by picking the right tool for the right problem.
- Make sure to aim for cleaner/elegant code when crafting your scripts, you saw the difference that the Switch statement can make against the if/else equivalent in that regard. Your future you and others will definitely praise you for that (hopefully).
- In the next article we will be taking a look at for loops and while loops, so stay tuned!
About the author
This author pledges the content of this article is based on professional experience and not AI generated.
View all my tips
Article Last Updated: 2022-03-24