Windows PowerShell’s If -AND

Introduction to The Windows PowerShell If -AND Statement

One of the best statements for filtering data is the 'If' clause.  For scripts that require precise flow control you could incorporate PowerShell's -And,  the benefit is that your test could now include multiple conditions.

Topics for PowerShell’s If -And Statement


Introduction to the PowerShell ‘If’ -And Statement

The key point is that you only need one ‘If’.

If (condition1 -And condition2) {Do stuff}
# An alternative explanation would be

If (test1 -And test2) {
execute block command when true

Summary:  The PowerShell ‘If’ conditionally executes a statements, depending on the truth of the test expression.

Example 1: Basic ‘If’ Test

If you are new to PowerShell’s implementation of If statement then it’s worth starting with a plain ‘If’ flow control before adding -And.

$Calendar = Get-Date
If ($Calendar.Month -eq ‘5’) {"This month is May"}
Else {"Not May"}

Learning Points

Note 1:  Trace the construction, and separate into two components: if (test) and {what to do}.

Note 2:  Avoid over-think; there is no ‘Then’ in a PowerShell ‘If’ statement.  My advice is that instead of worrying about ‘Then’, pay close attention to the two types of bracket.  Furthermore, there is no endif in PowerShell as there is in VBScript.

Note 3:  To double check your understanding, try amending, $Calendar.Month -eq ‘5’ to a different number, such as:  ’12’.  Once you have done that, change: Else {something different}.

Example 2: PowerShell If -And Script

The purpose of this script is merely to test different dates and compare them with today’s date, which is held by the variable $Calendar.

# PowerShell If AND Statement Simple Example
$Calendar = Get-Date
If ($Calendar.Day -eq ’25’ -And $Calendar.Month -eq ’12’) {
"Christmas Day"
Else {
"It's not Christmas yet! " + $Calendar.Month +"/" +$Calendar.Day

Multiple -And Conditions

Once your flow control works with one -And, it’s straightforward (if a little clumsy) to append more -And conditions.  Avoid ‘overthink’, you only need one set of (parenthesis brackets).

Here is an additional example with a few more statements containing -And

$Calendar = Get-Date
If ($ -eq ’25’ -And $Calendar.Month -eq ’12’) {"Christmas Day"}
ElseIf ($ -eq ‘4’ -And  $Calendar.Month -eq ‘7’) {"4th of July"}
ElseIf ($ -eq ‘1’ -And $Calendar.Month -eq ‘5’) {"May Day"}
Else {"It’s not Christmas today!"}

Note 4:  Pay close attention to the (first parenthesis).  In particular find the two tests: ".day -eq ’25’ ", also ".Month -eq ’12’ ".  My first point is they are separated by -And.  My second point is there is only one set of (condition brackets).

Note 5:  I included a few ElseIfs and a final Else statement to give the script a little more context, and to give ideas for modifying your scripts.

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

Example 3: PowerShell -AND Statement

Here is an example using logic to check whether you have a standard installation of your Microsoft Windows operating system.

If ($env:SystemDrive -eq "C:" -And $env:SystemRoot -eq "C:\Windows")
"This looks like a standard Windows installation"}
Else { "Non standard Windows installation" }

Note 5: There are no commas in this construction, in particular, there is no special syntax before the -And.

Example 4: PowerShell -Or Example

The reason for including this example is that -Or follows the same pattern as PowerShell’s -And.

While this script is designed to test the tiny ‘-Or’ syntax, it has lots of extraneous code which changes the startupType to manual.  The sole purpose of this convoluted layout is so that you can check the logic and thus understand how -Or works in PowerShell.

$NameSrv = ‘Spooler’
Set-Service $NameSrv -startupType manual
$Service = Get-WmiObject win32_service -filter "NAME = ‘$NameSrv’"
$Service | Ft Name, Startmode
if ($Service.Startmode -eq "Manual" -Or $Service.Startmode -eq "Disabled") {
Set-Service $NameSrv -startuptype Automatic }
$Service = Get-WmiObject win32_service -filter "NAME = ‘$NameSrv’ "
$Service | Ft Name, Startmode

Production script:
In real life you may want to strip the code down, and append a command to actually start the spooler service.

$Service = Get-WmiObject win32_service -filter "NAME = ‘Spooler’"
if ($Service.Startmode -eq "Manual" -Or $Service.Startmode -eq "Disabled") {
Set-Service ‘Spooler’ -startuptype Automatic }
Start-Service ‘Spooler’

Note 6: It’s always difficult to get the balance between example scripts that illustrate a point and those that do useful work.

Note 7: Once If statements get complicated it’s time to investigate PowerShell’s Switch parameter.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Researching PowerShell’s If -And

For more information refer to the built-in About_If file

Get-Help About_If

See more about PowerShell Comparison Operators ยป

Summary of PowerShell’s If -And Construction

When it comes to filtering output, one of the oldest and best statements is the ‘If’ clause.  As usual, the secret of understanding the syntax is to pay close attention to the style bracket.  If (parenthesis for the test) and {braces for the action}.  Once you have mastered the basic ‘If’ statement, then extend your capabilities by introducing ‘-And’.

If you like this page then please share it with your friends


See more Windows PowerShell flow control examples

PowerShell Home  • PowerShell If Statement  • PowerShell ElseIf   • Free Permissions Analyzer

Conditional Operators  • PowerShell -Match  • PowerShell -Like  • PowerShell -Contains

PowerShell Comparison Operators  • PowerShell Syntax   • Where Filter  • PowerShell Else

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.