You are on page 1of 5

1/15/2015

Hey,ScriptingGuy!HowCanIUsetheIfStatementinWindowsPowerShell?Hey,ScriptingGuy!BlogSiteHomeTechNetBlogs

All About
Windows Server

Cloud Platform
Blogs

Datacenter
Management

Client
Management

Virtualization,
VDI & Remote
Desktop

File & Storage &


High Availability

Windows Server
Management

Identity & Access

Hey, Scripting Guy! Blog


Learn about Windows PowerShell

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


Windows PowerShell?
ScriptingGuy1

6 May 2009 4:19 PM

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 GetHelp cmdlet to find Help, but when I use GetHelp 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. Im attaching a picture. Can you help me figure it out?
DZ

Hi DZ,
I will give you credit for persistence! In Windows PowerShell if you want to use GetHelp 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:
GetHelpabout_if
In Windows PowerShell 2.0, the GetHelp cmdlet uses a regular expression match to find Help topics. As seen here, both
cmdlet Help and about topic Help are searched.
PSC:\>GetHelpif
NameCategorySynopsis

NewModuleManifestCmdletCreatesanewmodulemanifest.
TestModuleManifestCmdletVerifiesthatamodulemanifest...
GetPfxCertificateCmdletGetsinformationabout.pfxcert...
about_ifHelpFileDescribesalanguagecommandyou...
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 handson labs and uses realworld examples to show the use of Windows
PowerShell.

http://blogs.technet.com/b/heyscriptingguy/archive/2009/05/06/howcaniusetheifstatementinwindowspowershell.aspx

1/5

1/15/2015

Hey,ScriptingGuy!HowCanIUsetheIfStatementinWindowsPowerShell?Hey,ScriptingGuy!BlogSiteHomeTechNetBlogs

In VBScript the IfThenEnd 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 IfThen End If statement must conclude with End If.
End If is two words, not one word.

The VBScript IfThenEnd If statement is seen in the DemoIf.vbs script.


DemoIf.vbs
a=5
Ifa=5Then
WScript.Echo"aequals5"
EndIf
In the Windows PowerShell version of the IfThenEnd 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($aeq5)
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.
{
'$aequals5'
}
The Windows PowerShell version of the DemoIf.vbs script is the DemoIf.ps1 script.
DemoIf.ps1
$a=5
If($aeq5)
{
'$aequals5'
}
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
Ifa=5Then
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, its 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

http://blogs.technet.com/b/heyscriptingguy/archive/2009/05/06/howcaniusetheifstatementinwindowspowershell.aspx

2/5

1/15/2015

Hey,ScriptingGuy!HowCanIUsetheIfStatementinWindowsPowerShell?Hey,ScriptingGuy!BlogSiteHomeTechNetBlogs

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

notmatchregular 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:
PSC:\>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:
PSC:\>if($true){"itstrue"}
itstrue
If the condition evaluates to false, the script block does not execute. This is seen here:
PSC:\>if($false){"itstrue"}
PSC:\>
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.
PSC:\>$a=1;If($a=12){"itstrue"}
itstrue
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 IfElseEnd 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
Ifa=5Then
WScript.Echo"aequals5"
Else
WScript.Echo"aisnotequalto5"
EndIf
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($aeq5)
{
'$aequals5'
}
Else
{
'$aisnotequalto5'
}
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
Ifa=5Then
WScript.Echo"aequals5"
ElseIfa=3Then
WScript.Echo"aequals3"
Else
WScript.Echo"adoesnotequal3or5"
EndIf
EndIf

http://blogs.technet.com/b/heyscriptingguy/archive/2009/05/06/howcaniusetheifstatementinwindowspowershell.aspx

3/5

1/15/2015

Hey,ScriptingGuy!HowCanIUsetheIfStatementinWindowsPowerShell?Hey,ScriptingGuy!BlogSiteHomeTechNetBlogs

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($aeq5)
{
'$aequals5'
}
ElseIf($aeq3)
{
'$aisequalto3'
}
Else
{
'$adoesnotequal3or5'
}
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

Tweet

Share

Save this on Delicious

Comments
17 Jun 2013 1:50 PM
Suparno

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

BrianJester

21 Aug 2013 10:35 PM

Thank you
21 Aug 2013 10:49 PM
Ed Wilson

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


7 Oct 2014 6:02 PM
Steve Smith

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 TestConnection 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

Victor Ashiedu

3 Nov 2014 2:31 PM

good stuff

http://blogs.technet.com/b/heyscriptingguy/archive/2009/05/06/howcaniusetheifstatementinwindowspowershell.aspx

4/5

1/15/2015

Hey,ScriptingGuy!HowCanIUsetheIfStatementinWindowsPowerShell?Hey,ScriptingGuy!BlogSiteHomeTechNetBlogs
17 Dec 2014 4:56 PM
JPJ

"it's true" not "its true"


:

http://blogs.technet.com/b/heyscriptingguy/archive/2009/05/06/howcaniusetheifstatementinwindowspowershell.aspx

5/5

You might also like