Posey's Tips & Tricks

How To Perform Conditional Logic in PowerShell

While you wait for PowerShell to add support for ternary operators, here's a method you can use now to evaluate Boolean conditions without the need to write If – Then – Else statements.

If you have been using PowerShell for a while, then you are no doubt familiar with If – Then – Else statements. As handy as these statements can be, there are some ways to perform conditional logic in PowerShell without having to use If – Then – Else.

Microsoft announced last month that the forthcoming PowerShell 7 release will include support for the use of ternary operators. These operators allow you to perform a conditional operation without the overhead involved in writing If – Then – Else statements.

The new type of ternary operation consists of an evaluation (such as a comparison between two values), a question mark and two possible outcomes separated by a colon. If, for example, you wanted to evaluate whether 10 was greater than 20, the expression might look something like this:

10 -GT 20 ? 'Yes' :  'No'

As you can see, the first part of the command is the evaluation, which uses an operator (-GT) to compare two values (10 and 20). The evaluation is separated from the possible outcomes by a question mark. The possible outcomes (yes and no) are separated from one another by a colon.

Unfortunately, this technique is not yet available for general use. However, there is a method that you can use today that will allow you to evaluate Boolean conditions without the need to write If – Then – Else statements.

Let's suppose for a moment that we have a PowerShell script that uses a variable named $State, and we periodically reference that variable throughout a script to determine if a particular error is being detected. For the sake of this example, let's assume that the $State variable can be set to either 'Normal' or 'Error'.

Assigning a value to the state variable works in the same way that you might assign a value to any other variable. If you wanted to set $State to 'Normal', for example, you could use a command like this one:

$State = 'Normal'

Likewise, if you wanted the $State variable to reflect an error condition, you could use this command:

$State = 'Error'

With that said, the usual way to check if the script was encountering an error condition would be to use an If – Then statement to check the value of the $State variable, and then take some sort of action based on the variable's contents. However, there is an easier way to get the job done.

Rather than using an If – Then – Else command every time you want to check the $State variable and then taking action based on what you discover, you can embed all of the possible values and responses into a hash table. Then, you simply reference the hash table any time you want to check the variable. Let me show you how this works.

Suppose that the script starts out in a normal state. We will start out with this variable assignment:

$State = 'Normal'

Now, let's set up our hash table. In this case, I am just going to use some simple blocks of text that will be displayed in response to the variable's contents, but it is possible to take other actions. I'm just trying to keep things simple. Here is what the array might look like:

$Health = @{$True = 'The script is healthy'; $False='An error has occurred'}

Now, we can compare the contents of the $State variable against the word Normal by using this command:

$Health[$State -EQ 'Normal']

Notice that the variable evaluation is being made within the context of the hash table. As such, if the $State variable contains the word Normal, then the command will return a value of true, which will cause the script to return a message stating that the script is healthy. Otherwise, the script will return a value of false, which will produce a message stating that an error has occurred. You can see an example of this in Figure 1.

[Click on image for larger view.] Figure 1: I am using a hash table to take action based on a variable's contents.

About the Author

Brien Posey is a 22-time Microsoft MVP with decades of IT experience. As a freelance writer, Posey has written thousands of articles and contributed to several dozen books on a wide variety of IT topics. Prior to going freelance, Posey was a CIO for a national chain of hospitals and health care facilities. He has also served as a network administrator for some of the country's largest insurance companies and for the Department of Defense at Fort Knox. In addition to his continued work in IT, Posey has spent the last several years actively training as a commercial scientist-astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space. You can follow his spaceflight training on his Web site.

Featured

comments powered by Disqus

Subscribe on YouTube