PowerShell Basics: ElseIf Statement

PowerShell Basics_ ElseIf Statement

Introduction to PowerShell’s Else If Logic

PowerShell’s ‘ElseIf’ statement comes under the umbrella of flow control.  Once you master the basic ‘If’ construction then you can increase the scope of your script by adding extra ‘ElseIf’ statements to the logic control.

Topics for PowerShell’s ElseIf Statement

Begin With The Plain ‘If’ Statement

Let us get started by mastering PowerShell’s basic ‘If’ construction.  All that you need here is a condition or test, followed by the block command payload.

Note in passing that PowerShell employs different types of bracket for each component, the (parenthesis style of bracket are for the first part, namely the condition), while {braces are for the block command}.
If (condition) {Block Command}
Here is a different explanation of the same ‘If’ construction:
If (test) { execute when true }
Summary:  The PowerShell ‘If’ conditionally executes what’s inside the {curly brackets}, depending on the truth of the test expression.

Example 1: Plain PowerShell ‘If’

# Trivial PowerShell If Example
$Number = 10
if ($Number -gt 0) {"$Number is greater than zero"}

Learning Points

Note 1:  Separate the If statement into two components: if (test) and {what to do}, then study each component of the PowerShell construction.

Note 2:  Avoid over-think; remember that there is no ‘Then’ in a PowerShell ‘If’ statement.  Incidentally, for those familiar with VBScript there is no endif in PowerShell.

Example 2: PowerShell ElseIf

Let us extend my trivial ‘If’ example by introducing an ‘ElseIf’ statement.  Incidentally, while ElseIf is not case sensitive, it does highlight the two words ‘Else’ and ‘if’.

# Simple PowerShell ElseIf Example
$Number = -10
If ($Number -gt 0) {"$Number is bigger than zero"}
ElseIf ($Number -lt 0) {"$Number is negative"}

Note 3: Do check the logic of each line,  -gt is PowerShell’s way of saying ‘Greater than’, and -lt means ‘Less than’.

PowerShell’s Else If

In this example I cannot get Else If, to work; what I find is that when there is a space between the Else and If, PowerShell generates an error.  What happens is I get message from PowerShell saying: ‘Missing block statement’.

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 ElseIf and Plain Else

It’s good practice to add a final Else statement.  This catch-all will check for anything that slips through your ElseIf logic.  For example, what if the value of $Number was precisely zero?

# Simple PowerShell ElseIf Example
$Number = -10 +10
if ($Number -gt 0) {
"$Number is bigger than zero"
ElseIf ($Number -lt 0) {
"$Number is negative"
Else {
"This number appears to be zero"

Example 4: Check If a Service is Installed and Working

Here is a real-life example of PowerShell ElseIf script, it uses the ‘Display’ property of the Windows spooler service.

# PowerShell script to check whether the spooler service is working
$SrvName = "Print Spooler"
$Service = Get-Service -display $SrvName -ErrorAction SilentlyContinue
if (-Not $Service) {$SrvName + " is not installed on this computer."}
ElseIf ($Service.Status -eq "Running") {$SrvName + " is working." }
ElseIf ($Service.Status -eq "Stopped") {$SrvName + " is not working." }
Else {"Guy is baffled "}

Note 4:  In addition to that final ‘Else’, this example uses multiple ElseIf conditional tests, however, for scripts that need even more complex logic I prefer ‘PowerShell’s Switch parameter‘.

Note 5:  See more on -ErrorAction SilentlyContinue

Researching PowerShell’s Else If Logic

For more information on using this logical construction refer to PowerShell’s built-in About_IF file

Get-Help About_If

For example, the About_If file reminds us that when a test is true, then after executing the {Statement}, PowerShell exits.  However, should the test be false then PowerShell continues to the next test.

Get more help on PowerShell’s About files »

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 5: PowerShell ElseIf Checks Help File

This example has an important task, and that is to check that we have the name of an actual file.  Remember that second (test statement) followed by a second {Block Script}.

# Help on PowerShell's ElseIf statements
$File = Get-Help About_scope
If ($File -Match "The if Statement") {"We have the correct help file"}
ElseIf ($File.Length -lt 1) {"Check the file name and its location"}
Else {"File exists, but does not contain info about the 'If statement'"}

Learning Points

Note 6:  The advantage of ElseIf over plain Else, is that we can introduce multiple tests.  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 7: To trigger the final ‘Else’, try changing:
$File = Get-Help About_If
$File = Get-Help about_scope

Note 8:  Alternatively, see more about the PowerShell ElseIf statement at Microsoft’s site.

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)

PowerShell’s Else Construction

PowerShell’s ‘Else’ acts as a safety net for flow logic.  Following on from the ‘If’ command you often you have multiple ElseIf statements, with a final plain ‘else’ statement.

See more on PowerShell’s plain ‘Else’ statement »

Summary of PowerShell’s ElseIf Construction

One of the oldest, and one of the best, statements for filtering data is the ‘If’ clause.  Nevertheless it’s always worth a refresher on the basic ‘If’ statement, before progressing to the more versatile ‘ElseIf’.  The secret of understanding PowerShell’s implementation of If and ElseIf is to pay close attention to the style bracket.  ElseIf (parenthesis for the test) and {braces for the action}.

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.