Guy recommends :
Free SolarWinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



PowerShell 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 appending, 'Else' and 'ElseIf' to logic statements.

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 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 Else If

I cannot get Else If, to work; what I find is that when there is a space between the Else and If it does not work for me.  What what happens is I get an error message: 'Missing block statement'.

Guy Recommends: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

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.

Download your free copy of WMI Monitor

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
Clear-Host
$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 ElseIfs, however, for scripts that need even more complex logic I prefer 'PowerShell's Switch'.

Note 5:  See more on -ErrorAction SilentlyContinue

Researching PowerShell's Else If Logic

For more information refer to PowerShell's built-in About_IF file

Get-Help About_If

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

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.

Download a free trial of the Network Performance Monitor.

Example 5: PowerShell ElseIf Help File

This example has an important 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"}

Learning Points

Note 6:  The advantage of ElseIf over plain Else, is that we can introduce more 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
to
$File = Get-Help about_scope

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

Guy Recommends:  SolarWinds' Free Bulk Import ToolFree Download of 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 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:

  1. Bulk-import new users into Active Directory.
  2. Seek and zap unwanted user accounts.
  3. Find inactive computers.

Download your FREE bulk import tool.

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 versitile 'ElseIf'.  The secret of understanding PowerShell's impementation 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 examples

PowerShell Home  • PowerShell If Statement  • PowerShell ElseIf  • PowerShell If -Not

PowerShell comparison operators  • PowerShell If -And  • PowerShell If -Or

Where Filter   • Loops  • Brackets  • -Match  • Switch  • Conditional Operators

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.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

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.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2012 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: