Powershell – If -And & If -Or Statements


To totally unlock this section you need to Log-in

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.

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
}

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"}

Note 1: separate the two components of this structure as the following: if (test) {what to do}.

Note 2: avoid over-think; there is no Then in a PowerShell If statement. Our 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: If -And Code

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. Take note of the multiple conditions (two) in the definition of the If statement:

# PowerShell If And Statement Simple Example
Clear-Host
$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:

Clear-Host
$Calendar = Get-Date
If ($Calendar.day -eq '25' -And $Calendar.Month -eq '12') {"Christmas Day"}
ElseIf ($Calendar.day -eq '4' -And  $Calendar.Month -eq '7') {"4th of July"}
ElseIf ($Calendar.day -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: we 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.

Example 3: -And Statement

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

Clear-Host
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: -Or Statement

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.

Clear-Host
$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 is 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.

Multiple (-And) (-Or) within a single If statement

The following scenario is when you need to specify multiple -And and/or -Or statements in you If structure, so based on being able to code an If statement, we could , for example, create two simple If statements in either of the following fashions:

If ($someAttribute -eq $false -Or $someAttribute -eq $Null){ }

Or the following:

If (($someAttribute -eq $false) -or ($someAttribute -eq $Null)){ }

Then we should be able to do a combined effort:

If ((($someAttribute -eq $false -Or $someAttribute -eq $Null) -And ($someUser -eq “UserID123”))){
       Write-Host “Switching to True”
       Set-QADUser $someUser -Service “MyDomain.org” -ObjectAttributes @{$someAttribute = $True}
       If (!$?) {Write-Host “Error: $($error[0])”}
}

So if $someAttribute is either $false or $Null AND #someUser equals “UserID123″ then do something...in this case we switch the attribute someAttribute to $true and do some error checking.