EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial Else If in PowerShell
Secondary Sidebar
PowerShell Tutorial
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Else If in PowerShell

By Chirag NagarekarChirag Nagarekar

Else If in PowerShell

Introduction to Else If in PowerShell

If / else conditions are the most useful conditions in a scripting language and you may want to use multiple times while writing script. If the first condition in If the statement fails then the second stage is ElseIf statement. InElseIfblock you can also specify your conditions or test values. If the above two conditions fail then the last block is Else, which doesn’t require any condition to check and it will be directly executed when If and ElseIf statement fails.

Syntax

if (condition) {<Statement List 1>}
elseif (condition) {<Statement List 2>}
else {<Statement List 3>}

How to Use the IF Condition?

Below is the detail explanation of if condition:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,700 ratings)

1. Flow chart for If condition

Flowchart1

How Does If condition works?

As shown in the above diagram, If the statement contains a condition. If condition satisfies then it executes the block. If there are multiple if statements then script checks each if statement condition and executes whichever is true.

If the statement is used to evaluate the condition. If the condition succeeds then block statement runs. You can specify more than one or more conditions in If statement, depending upon the operators used (comparison, Boolean, bitwise) statement evaluates condition.

Example

Code:

if((Get-Service Spooler).Status -eq "Running"){
Write-Output "Spooler Service is Running"
}
if((Get-Service Spooler).Status -eq "Stopped"){
Write-Output "Spooler Service is Stopped"
}
if((Get-Service Power).Status -eq "Running"){
Write-Output "Power Service is running"
}

Output:

two conditions

Explanation: In the above example, two conditions (first and last) are getting satisfied so two blocks are executed. But according to programming standard multiple If statements are not recommended as it takes more execution time. Instead, we can use If / elseif / else block.

2. Nested If statement

Syntax:

if (condition) {
if (condition1) {"Execution Statement1"}
if (condition2) {
"Execution Statement2"
if (condition3) {"Execution Statement3"}
}
}

Example

Code #1: Consider the below example for nested If statement.

$srv = Get-Service Spooler
if($srv){
if($srv.Status -eq "Running"){"Service is Running"}
if($srv.Status -eq "Stopped"){"Service is Stopped"}
}

Code #2:

$srv = Get-Service Spooler
if($srv){
if($srv.Status -eq "Running"){"Service is Running"}
if($srv.Status -eq "Stopped"){"Service is Stopped"}
}

Output:

Service exists

Explanation: In this example, first it checks the If Service exists, and if service it exists then it enters the block and again checks if service is Running or Stopped and executes their block accordingly. This is the perfect example of an explanation of nestedIfloop.

If /else functionality in PowerShell

Writing multiple if statements are not a good idea if the condition is already satisfied. So that we can use else statement if there is the only single condition to check.

Syntax

if (condition1) {"Execution Statement1"}
else {"Execution Statement2"}

Flowchart If / else condition

Flowchart2

Example

Code:

Stop-Service Spooler
if((Get-Service Spooler).Status -eq "Running"){"Spooler service is running"}
else{"Spooler service is stopped"}

In the above example, Spooler service is stopped so else block is executed without further conditions check.

Output:

Else If in PowerShell - 3

Nested If /else statement

Below are the example for nested if statement:

Code: #1

if (condition1) {
if (condition2) {"Execution Statement2"}
else{"Execution Statement2"}
}
else{
"Execution Statement1"
if (condition3) {"Execution Statement3"}
else {"Execution Statement3"}
}

Code: #2

$srv = Get-Service Spooler -ErrorAction Ignore
if($srv){
if($srv.Status -eq "Running"){"Spooler Service is running"}
else{"Spooler Service is not running"}
}
Else{
Write-Output "There is no service with name Spooler"
}

Output:

Else If in PowerShell - 4

If / elseif  /else functionality PowerShell

In the above examples, we have seen that if and else conditions are not satisfied if we have multiple if conditions, so it checks every If condition and when they are not true then else statement is executed. Here, to meet execution time criteria there is another elseif statement that we can use.

Syntax:

if (condition1) {"Execution Statement1"}
elseif (condition2) {"Execution Statement2"}
elseif (condition2) {"Execution Statement3"}
else {"Execution Statement4"}

Flowchart If / elseif / if condition

Flowchart3

Example

Code:

$srv = Get-Service Spooler -ErrorAction Ignore
if($srv.Status -eq "Running"){
"Spooler Service is running"
}
elseif($srv.Status -eq "Stopped"){
"Spooler Service is stopped"
}
else{
"Spooler service is in Start Pending or Stopped pending status"
}

Output:

Else If in PowerShell - 5

Nested If / elseif /else statement

Below are the example to nested if statement:

Code:

[int]$num = Read-Host "Enter Number"
if($num -ge 10){
if($num -lt 15){"Number is less than 15"}
elseif(($num -ge 15) -and ($num -lt 20)){
"Number is between 15 and 20"
}
else{"Number is greater than 20"}
}
elseif(($num -ge 5) -and ($num -lt 10)){
"Number is greater than 5 and less than 10"
}
else{
if($num -gt 2){"Number is greater than 2"}
else{"Number is less than 2"}
}

Output:

Nested If

Multiple Conditions

You can use multiple conditions check within a single If or ElseIf statement and depends on which operators you use according to your requirement. For Example,

Code #1

$srv = Get-Service Spooler
if(($srv.Status -eq "Stopped") -and ($srv.StartType -eq "Automatic")){
"Spooler Service Starttyp is Automatic but in Stopped status"
}
else{"Service is Running or Start type is not Automatic"}

Output:

multiple conditions

Code #2

$srv = Get-Service Spooler
if(($srv.Status -eq "Stopped") -or ($srv.Status -eq "Running")){
"Spooler Service is in Stopped or Running State"
}
else{"Spooler Service is StopPending or StartPending State"}

Output:

multiple conditions

Like the above examples, you can use multiple or single conditional operators in If or elseif condition.

Recommended Articles

This is a guide to Else If in PowerShell. Here we discuss how to use if condition, and use multiple or single conditional operators in If or elseif condition. You can also go through our other related articles to learn more –

  1. PowerShell Switch Statement
  2. PowerShell Wildcards
  3. PowerShell Grep
  4. PowerShell Rename Folder
Popular Course in this category
Microsoft Power BI Training (6 Courses, 4 Projects)
  6 Online Courses |  4 Hands-on Projects |  45+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more