If…Then…Else


Definition: Conditionally executes a group of statements, depending on the value of an expression.

 

If you know how to use If Then statements in VBScript then you have a nice head start on using If Then statements in Windows PowerShell. After all, the underlying philosophy is exactly the same; all you have to do is learn the Windows PowerShell syntax.

 

With that in mind, let’s take a look at a simple If Then statement in Windows PowerShell. Before we go much further, we should note that we could have typed the entire statement on a single line. We couldhave, but we didn’t, mainly because we wanted to keep things as simple and easy-to-follow as possible.

 

But we could have.

 

Here’s our example which, after assigning the value 5 to the variable $a, uses an If Then statement to determine whether or not $ a isless then 10, and then echoes back the appropriate message:

 

$a = 5

if ($a - gt10)
    {"The value is greater than 10."}
else
    {"The value is less than 10."}

 

Right off the bat you should notice two things. First, although we refer to this as an If Then statement, we never actually use the word Then . Instead, all we need is the keyword If followed by the condition we are checking for, enclosed in parentheses:

 

if ($a - gt10)

 

The second thing to notice?There’s no EndIfkeyword (or its equivalent). In Windows PowerShell you typically don’t need to using “ending” statement like EndIf, Loop, Next, etc.

Immediately following the condition we have the action we want to take if the condition is true, that is, if $a really is greater than 10. These actions must be enclosed in curly braces, like so:

 

{"The value is greater than 10."}

 

So far what we’ve looked at is equivalent to the following VBScript code:

 

If a > 10 Then
    Wscript.Echo"The value is greater than 10."

 

All we have to do now is add the Else statement. We do that simply by typing in the keyword Else followed by the action to be taken should the condition notbe true. In other words:

 

else
    {"The value is less than 10."}

 

And, yes, we could include an ElseIf(or two or three or …) in here as well. In fact, here’s a revised If Then statement that includes an ElseIf. If the value of $a is reda message to that effect will be echoed to the screen; if the value of $a is white elseif   ( $a – eq"white")– a message to thateffect is echoed to the screen. (Note that the ElseIfcondition must be enclosed in parentheses, and the ElseIfaction must be enclosed in curly braces.) Otherwise ( else) a message saying that the color is blue is echoed back to the screen.

 

Here’s what our new example looks like:

 

$a = "white"

if ($a - eq"red")
    {"The color is red."}
elseif($a - eq"white")
    {"The color is white."}
else
    {"The color is blue."}