Hey, Scripting Guy! How Can I Use the If Statement in Windows PowerShell?

Hey, Scripting Guy! How Can I Use the If Statement in Windows PowerShell?

  • Comments 6
  • Likes

Hey, Scripting Guy! Question

Hey, Scripting Guy! I have a problem with a script I am trying to write. I have to evaluate between several conditions as they come into the script, but I do not understand the way the If statement in Windows PowerShell works. I even tried to use the Get-Help cmdlet to find Help, but when I use Get-Help If, it says it cannot find Help for that topic. Surely Windows PowerShell contains an If statement. One good thing is the error messages in Windows PowerShell point you in the appropriate direction. I tried several things, and finally got the statement to work. However, it is now giving me bogus results. I’m attaching a picture. Can you help me figure it out?

--DZ

Image of trial-end-error attempts to make If statement work

 

SpacerHey, Scripting Guy! Answer

Hi DZ,

I will give you credit for persistence! In Windows PowerShell if you want to use Get-Help to learn about something, look for an "about topic". Interestingly, if you were using Windows PowerShell 2.0 (currently in CTP 3), your first query would have worked and you would have found the about_if topic. Here is the Help query that you should have used:

Get-Help about_if

In Windows PowerShell 2.0, the Get-Help cmdlet uses a regular expression match to find Help topics. As seen here, both cmdlet Help and about topic Help are searched.

PS C:\> Get-Help if

Name                              Category  Synopsis
----                              --------  --------
New-ModuleManifest                Cmdlet    Creates a new module manifest.
Test-ModuleManifest               Cmdlet    Verifies that a module manifest ...
Get-PfxCertificate                Cmdlet    Gets information about .pfx cert...
about_if                          HelpFile  Describes a language command you...

This week we are looking at scripting with Windows PowerShell. Windows PowerShell is installed by default on Windows Server 2008 R2 and Windows 7. It is an optional installation on Windows Server 2008, and a download for Windows Vista, Windows XP, and Windows Server 2003. The Windows PowerShell Scripting Hub is a good place to start using Windows PowerShell. An excellent book for learning Windows PowerShell is the Microsoft Press book, Microsoft Windows PowerShell Step by Step. This book has many hands-on labs and uses real-world examples to show the use of Windows PowerShell.

In VBScript the If…Then…End If statement was somewhat straightforward. There were several things to be aware of:

The If and the Then statements must be on the same line.

The If…Then… End If statement must conclude with End If.

End If is two words, not one word.

The VBScript If…Then…End If statement is seen in the DemoIf.vbs script.

DemoIf.vbs

a = 5
If a = 5 Then
 WScript.Echo "a equals 5"
End If

In the Windows PowerShell version of the If…Then…End If statement, there is neither a Then keyword nor an End If statement. From a typing perspective, the Windows PowerShell If statement is easier. This simplicity, however, comes with a bit of complexity. The condition that is evaluated in the If statement is positioned in a set of parentheses. In the DemoIf.ps1 script, we are checking whether the variable $a is equal to 5. This is seen here:

If ($a –eq 5)

The code that is executed when the condition is true is positioned inside a pair of braces (curly brackets). Code inside a pair of curly brackets is called a script block in Windows PowerShell, and script blocks are everywhere. The script block for the DemoIf.ps1 script is seen here.

{
   '$a equals 5'
}

The Windows PowerShell version of the DemoIf.vbs script is the DemoIf.ps1 script.

DemoIf.ps1

$a = 5
If($a -eq 5)
 {
   '$a equals 5'
 }

The hard part about how to work with the Windows PowerShell If statement is learning the comparison operators. In VBScript the equal sign (=) is used as an assignment operator. It is also used as an equality operator for comparison. On the first line of code, the variable a is assigned the value 5. This uses the equal sign as an assignment. On the next line of code, the If statement is used to see whether the value of a is equal to the number 5. On this line of code, the equal sign is used as the equality operator. This is seen here:

a = 5
If a = 5 Then

In simple examples such as this, it is fairly easy to tell the difference between an equality operator and an assignment operator. In more complex scripts, however, things could be confusing. Windows PowerShell removes that confusion by having special comparison operators. These are seen in Table 1. As mentioned earlier, this clarity comes with a bit of confusion, until you take the time to learn the PowerShell comparison operators. One thing that might help is to realize that the main operators are two letters long. The use of -eq stands for "equals," and if you got that one right, it’s not a stretch to understand that -ne stands for "not equal." The one that used to trip me up was –ge for "greater than or equal to." For some reason, back when I was first learning Windows PowerShell, I would always type –gte for "greater than or equal to." Anyway, examine Table 1, print it out if you have to, and after several scripts the comparison operators will seem perfectly natural.

Table 1 Comparison Operators
Operator Description Example Result

-eq

equals

$a = 5 ; $a -eq 4

False

-ne

not equal

$a = 5 ; $a -ne 4

True

-gt

greater than

$a = 5 ; $a -gt 4

True

-ge

greater than or equal to

$a = 5 ; $a -ge 5

True

-lt

less than

$a = 5 ; $a -lt 5

False

-le

less than or equal to

$a = 5 ; $a -le 5

True

-like

wildcard comparison

$a = "This is Text" ; $a -like "Text"

False

-notlike

wildcard comparison

$a = "This is Text" ; $a -notlike "Text"

True

-match

regular expression comparison

$a = "Text is Text" ; $a -match "Text"

True

-notmatch

regular expression comparison

$a = "This is Text" ; $a -notmatch "Text$"

False

Now for the hard part DZ: "Why did the last thing that you typed work incorrectly?" When you typed $a = 5, you used an assignment operator:

PS C:\> if ($a = 5) { "hi" }
hi

Remember that the If statement executes the script block if the condition evaluates to true. This can be illustrated perhaps more clearly by putting the $true variable into the condition as seen here:

PS C:\> if ($true) { "its true" }
its true

If the condition evaluates to false, the script block does not execute. This is seen here:

PS C:\> if ($false) { "its true" }
PS C:\>

Any assignment will evaluate to true, and therefore the script block is executed. In this example, we assign the value 1 to the variable $a. In the condition for the If statement, we assign the value of 12 to the variable $a. Any assignment evaluates to true, and the script block executes.

PS C:\> $a = 1 ; If ($a = 12) { "its true" }
its true

Rarely do you test a condition and perform an outcome. Most of the time, you have to perform one action if the condition is true, and another action if the condition is false. In VBScript you used the If…Else…End If construction. The Else clause went immediately after the first outcome to be performed if the condition were true. This is seen in the DemoIfElse.vbs script:

DemoIfElse.vbs

a = 4
If a = 5 Then
 WScript.Echo "a equals 5"
Else
 WScript.Echo "a is not equal to 5"
End If

In Windows PowerShell the syntax is not surprising. Following the closing curly brackets from the If statement script block, you add the Else keyword and open a new script block to hold the alternative outcome. This is seen here:

DemoIfElse.ps1

$a = 4
If ($a -eq 5)
{
 '$a equals 5'
}
Else
{
 '$a is not equal to 5'
}

Things become confusing with VBScript when you want to evaluate multiple conditions and have multiple outcomes. The Else If clause provides for the second outcome. You have to evaluate the second condition. The Else If clause receives its own condition, which is followed by the Then keyword. Following the Then keyword, list the code that you want to execute. This is followed by the Else keyword and a pair of End If statements. This is seen in the DemoIfElseIfElse.vbs script:

DemoIfElseIfElse.vbs

a = 4
If a = 5 Then
 WScript.Echo "a equals 5"
Else If a = 3 Then
 WScript.Echo "a equals 3"
Else
 WScript.Echo "a does not equal 3 or 5"
End If
End If

The Windows PowerShell DemoIfElseIfElse.ps1 script is a bit easier to understand because it avoids the double End If kind of scenario. For each condition that you want to evaluate, you use ElseIf (be aware that it is a single word). You put the condition inside a pair of parentheses, and open your script block. Here is the DemoIfElseIfElse.ps1 script:

DemoIfElseIfElse.ps1

$a = 4
If ($a -eq 5)
{
 '$a equals 5'
}
ElseIf ($a -eq 3)
{
 '$a is equal to 3'
}
Else
{
 '$a does not equal 3 or 5'
}

DZ, as a best practice, I generally avoid using the ElseIf type of construction from either VBScript or Windows PowerShell because there is a much better way to write the same code. We will examine that construction tomorrow. I hope that you enjoyed today's excursion into the If statement. Join us tomorrow. Until then, keep on scripting.

 

Ed Wilson and Craig Liebendorfer, Scripting Guys

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Hi guys, I need to create a script to execute this -

    (1) IF the program finds HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CSC\Start (REG_DWORD) = 4, then change the same key to 1 AND change HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CscService\Start to 2.

    (2) IF the program finds HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CscService\Start (REG_DWORD) = 4, then change the same key to 2 AND change HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CSC\Start to 1.

    How do I create a script (batch / powershell) for this in the easiest way. (I need to run this as an application in SCCM 2012)

  • Thank you

  • @BrianJester you are welcome. I am glad you found it helpful.

  • I am trying to check connection for IP address and delete DHCP lease if the connection is false. So far this is what I have.
    if (Test-Connection -ComputerName 10.5.5.100 -Count 1 -Quiet) -eq False {netsh dhcp server \\computername scope 10.5.5.0 delete lease 10.5.5.100

    I know both commands work but I cant get the syntax right

  • good stuff

  • "it's true" not "its true"
    :)