Introduction to The Windows PowerShell If Statement
PowerShell's 'If' statement comes under the umbrella of flow control. Once you master the basic construction then you can increase
its usefulness by appending, 'Else' and 'ElseIf' statements. Another
alternative would be to use 'Switch'.
As with so many PowerShell constructions, the type of bracket signifies how to break the script into sections.
It is worth emphasising that (parenthesis are for the first part, namely the condition), while {braces are for the block command}.
If (condition) {Do stuff} # Another explanation would be If
(test) { "Execute when true" }
Summary: The PowerShell 'If' conditionally executes a statements,
depending on the truth of the test expression.
# PowerShell If Example $Number = 10 if ($Number -gt 0) {"Bigger than zero"}
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 'If 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, "Bigger than Zero" to a different text
string, such as: "Less than nought". Once you have done that, set $Number to -1.
Example 1b PowerShell Script to Checks If a File Exists
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft 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.
Example 1b PowerShell If
-Not Statement to Check for a Service
# PowerShell script to check whether a service is installed Clear-Host
$SrvName = "Alerter" $Service = Get-Service -display $SrvName -ErrorAction
SilentlyContinue if (-not $Service) { $SrvName + " is
not installed on this computer." }
Note 6: This script uses the Display Name property of
the service. Remember in PowerShell 'If Then' does not exist.
Observe it's plain 'If'.
Note 7: Observe in passing the If -not construction,
which is sometimes abbreviated to an exclamation mark ! in PowerShell.
Note 8: This script cries out for an Else statement.
We need to know if the named service has been installed.
# PowerShell script to check whether a service is installed Clear-Host
$SrvName = "Print Spooler" $Service = Get-Service -display $SrvName -ErrorAction
SilentlyContinue if (-not $Service) {$SrvName + " is
not installed on this computer."} else {$SrvName + " is
installed." $SrvName + "'s status is: " + $service.Status }
Example 1c PowerShell If Statement To Check IP Addresses
Here is another real-life example of the 'If statement'. The idea is to
ping 20 IP Addresses. The logic says If the StatusCode is 0, then
display a label saying 'ON NETWORK'.
# PowerShell If Statement To Test Ip Addresses $i =1 $Ip =
"192.168.1." Write-Host "IP Address" Write-Host
"----------------------------------------" Do { $Ip4th = $Ip + $i
$Pingy = Get-WmiObject Win32_PingStatus -f "Address='$Ip4th'" if($Pingy.StatusCode
-eq 0) { "{0,0} {1,5} {2,5}" -f $Pingy.Address, $Pingy.StatusCode,"
ON NETWORK"} else {"{0,0} {1,5} {2,5}" -f $Pingy.Address,
$Pingy.StatusCode, " xxxxxxxxx" } $i++
} until ($i -eq 20)
Example 1d File Content Example of Plain 'If'
PowerShell has a batch of help files. One of these files contains help about the 'if' statement. In the example below,
$File references that file. $Content is set to the content of
the file. The third line attempts to match a string to the contents of the file.
# Help on PowerShell's if statements $File = Get-Help about_if
if ($File -match "The if Statement") { "We have the correct help
file" }
Learning Points
The above example is concerned with matching a string "The if Statement" to the contents of
the built in help file.
Guy Recommends: A Free Trial of the Network Performance Monitor
(NPM)
Solarwinds'
Orion 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.
Perhaps the NPM's best feature is the way it suggests solutions to network
problems. Its
second best feature is 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 take advantage of Solarwinds' offer.
This example deal with plain 'Else'. This is a simple command,
unlike ElseIf there is no second test construction, Else just follows on
to reflect what to do if the If statement is false.
# Help on PowerShell's Else statements $File = Get-Help about_if if
($File -match "The if Statement") {"We have the correct help file"} Else
{"The string is wrong"}
Learning Points
The best way to see how 'else' operates is to amend line 3 thus: ($File -match "The ifzz Statement").
Example 2b Checking If a Service Has Been Installed
# PowerShell script to check whether a service is installed Clear-Host
$SrvName = "Print Spooler" $Service = Get-Service -display $SrvName -ErrorAction
SilentlyContinue if (-not $Service) {$SrvName + " is not installed on
this computer."} else {$SrvName + " is installed."
$SrvName + "'s status is: " + $service.Status }
Example 2c PowerShell If -Not Logic
The purpose of this script is to employ -not logic to check for the
Alerter service. Once scenario is you are working with Windows 7
machines, and they no longer install this 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"}
# PowerShell ElseIf Example Using NetSh Clear-Host Write-Host "Firewall configuration for $env:computername"
$Fw = netsh firewall set opmode enable $Fw if($Fw -match
'ok'){write-Host "$env:username's job is done"} elseif($Fw -match
'requires elevation') {write-Host "Call for an administrator"}
else{write-Host "Nothing happened"} netsh firewall show opmode
Guy Recommends: Solarwinds' Free 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 to import the users. Optionally, you can
provide the name of the OU where the new accounts will be born.
There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:
This example has a real task, and that is to check that we have the name of an actual file.
Remember the second (test statement) followed by a second {Block Script}.
# Help on PowerShell's Elseif statements $File = Get-Help about_if if ($File -match "The if Statement") {"We have the correct help file"}
ElseIf ($File.Length -lt 1) {"Check file location"} Else {"File
exists, but does not contain text string"}
Note 1: The advantage of ElseIf over plain Else, is that we can introduce a new test. In the above example we use ElseIf to check if the length of the file is less than 1. To activate the 'ElseIf' block, set
$File to a non-existent file for example $File = Get-Help about_ifxx.
Note 2: To trigger the final 'Else', try changing:
$File = Get-Help about_if to $File = Get-Help about_scope
If you have time, you could add more 'ElseIf' statements to cater for other eventualities.
Alternatively, if the ElseIf construction is getting unwieldy, then try
the superior switch command.
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 'Else' and 'ElseIf'.
Incidentally, the 'Vehicle' for our tests reveals a whole family of about_zyx files. My point is there is no command : 'Get-help if',
but there is a help file called, 'about_if'. Furthermore, if you look in the PowerShell directory then you will see 'About'
files to assist with commands such as 'If' and 'ElseIf'. You can list
these 'About' files with the command:
Get-help about*
If you like this page then please share it with your friends
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.
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems.
Fortunately, Solarwinds
have created the
Free WMI Monitor so that you can actually see and understand these gems of
performance information. Take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.