PowerShell Basics: If -Not Conditional Operator

PowerShell Basics_ If -Not Conditional Operator

Introduction to Windows PowerShell’s If -Not Logic

Once you have mastered the basic ‘If’ statement, you just need to acquire the knack of extending the logic to embrace the PowerShell ‘If not equal’ syntax.

Topics for PowerShell PowerShell’s If -Not Conditional Operator

Construction of the PowerShell ‘If’ Statement

Let us get started by studying PowerShell’s ‘If’ logic.  The secret is to identify the two parts of the construction: (test condition) and {block command}.

It helps to keep one eye on PowerShell’s different types of bracket.  (The parenthesis style of brackets are used for the first part, namely the condition), while {braces denote the block command payload}.

If (condition) {Block Command}

Here is an alternative explanation of the same ‘If’ flow control:

If (test) {execute when true}

Summary:  The PowerShell ‘If’ conditionally executes a block statement, providing the test expression is true.

Example 1: Basic ‘If’ Statement

Think of this script as a preamble which checks whether the Alerter service is installed on your machine, and introduces the basic ‘If’ statement.   There is no -Not comparison here, that comes in Example 2.

# PowerShell script to check if a service is installed
$SrvName = "Alerter"
$Service = Get-Service -display $SrvName -ErrorAction SilentlyContinue
If ($Service) {$SrvName + " is installed on this computer."}
Else {"No Alerter service indicates Windows 7 or Server 2008"}

Learning Points

Note 1: The If (test) is simply this: can Get-Service find the $SrvName.  Try changing “Alerter” to “Print Spooler”

Note 2: Avoid over-think; there is no ‘Then’ in a PowerShell ‘If’ statement. Furthermore, there is no endif in PowerShell as would be in VBScript.

Example 2: PowerShell If -Not Conditional Operator

The purpose of this script is to check for the Alerter service, the reason being Windows 7 machines no longer install the Alerter service.

Observe how -Not reverses the ‘If’ logic compared with Example 1.

# PowerShell script to check if a service is -NOT installed
$SrvName = "Alerter"
$Service = Get-Service -display $SrvName -ErrorAction SilentlyContinue
If (-Not $Service) {$SrvName + " is not installed on this computer."}
Else {"You probably have $SrvName, thus machine is Vista or W2K3"}

Note 3: The -Not conditional operator has an alias of !  This is they only example of an alias for a PowerShell operator.

Guy Recommends: Free WMI Monitor for PowerShell (FREE TOOL)Solarwinds 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 for PowerShell so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guesswork 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.

SolarWinds WMI Monitor Download 100% Free Tool

Example 3: PowerShell If -ne

Here is a variation of the previous script, the only difference is that this example employs -ne [not equal] rather than -Not.

# PowerShell script to check if a service is NOT equal to ""
$SrvName = "Alerter"
$Service = Get-Service -display $SrvName -ErrorAction SilentlyContinue
If ($Service -ne "") {$SrvName + " is not installed on this computer."}
Else {"You probably have $SrvName, thus machine is Vista or W2K3"}

Note 4: This is a crude and forced example of -ne, a better example for ‘not equal’ would be testing numeric data.

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

Example 3a: PowerShell If -ne Numeric Data

If (Test numbers not equal) {Script block}

#PowerShell If Not Statement
$GuyNum = "12"
If($GuyNum -ne '7'){"Guy's number is not seven"}
Else {"Guy's number is $GuyNum "}

Note 6: My biggest problem with not equal is wanting to write -neq, when I should be typing: -ne.  So often it’s overthink that is my downfall!

Note 7: While this a pretty crude example, it does plant the idea that you could use other comparators such as greater than -gt, or less than -lt.

Guy Recommends:  Network Performance Monitor (FREE TRIAL)Review of Orion NPM v11.5

SolarWinds Network Performance Monitor (NPM) 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 on a 30-day free trial.

SolarWinds Network Performance Monitor Download 30-day FREE Trial

Example 4: PowerShell If -or

Following PowerShell’s If -Not or If -ne there are more variations on the logic, for example ‘-or’.

$NameSrv = 'Spooler'
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

Note 8: Do check the logic of your (test1 -or test2) statement.

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'

Guy Recommends:  SolarWinds Admin Bundle for Active Directory (FREE TOOL)Free Download Solarwinds Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD’s attributes, click and import the users.

Optionally, you can provide the name of the OU where the new accounts will be born. Download your FREE bulk import tool.

SolarWinds Admin Bundle Download 100% FREE Tool Bundle

If you need more comprehensive application analysis software, Download a free trial of SAM (Server & Application Monitor)

Researching Comparison Operators

For more detailed information refer to the built-in About_If file; alternatively, try the Comparison Operators help file:

Get-Help About_Comparison_Operators

See more about PowerShell Comparison Operators »

Summary of PowerShell’s If -Not 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 researching -Not logic.  Alternative strategies include, -ne, -And, also -or.

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

See more Windows PowerShell flow control examples

PowerShell Continue Statement  • PowerShell If Statement  • PowerShell ElseIf  • PowerShell Else

PowerShell Comparison Operators  • PowerShell If -And  • PowerShell If -Or   • PowerShell If -Not

Conditional Operators  • Where Filter  • PowerShell Real-life Techniques  • PowerShell Home

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.