EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial If Else 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

If Else in PowerShell

By Priya PedamkarPriya Pedamkar

if else in powershell

Introduction to If Else in PowerShell

We have learned from the IF statement in PowerShell that it gives us the power to decide the execution of any statement on the basis of certain conditions. But what if we want to execute another statement in case of IF condition gets failed or what if we have multiple situations where if one condition gets failed then it should check for other conditions. Let’s take an example, suppose we want to show student grades in percentage. Like if the grade is A than show message 50%, if a grade is B then 65% if the grade is C than 80% and If a grade is E show 90%. So to display different messages on the different grade IF statement is not enough, for such type of situation we can use IF ELSE of PowerShell. IF ELSE gives us the power to execute a different set of statements on the basis of weather condition expression if true or false. We will learn it in more detail in examples and in the syntax part.

Syntax:

In the below syntax we are checking condition expression 1 if this expression returns true then statement 1 will execute if expression 1 returns false it will execute statement 2.

if (<condition expression 1>)
{<statement 1>}
[else )
{<statement 2>}]

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Flowchart

In the below flow chart first, it will check for condition expression 1, if condition expression 1 returns true it will execute statement 1 if condition expression 1 returns false then statement 2 will execute that means it will execute else block if the condition of IF is false.

if else in powershell

Refer to the flow diagram given below for better understanding. Let me explain to you a real time situation where you would need to write else if. Suppose You have a server that is running and is connected to database d1, and we have another database d2. And we are writing a script that will check if database d1 is active or not. If database d1 is inactive than connect to another database d2.So to write a program for this we can use the if-else statement. In the if statement we will check the status of database d1 if it returns true, which means it is running so no need to connect to database d2. If database d1 status is false then it will connect to database d2 and our server will keep working.

How If Else Statement Works in PowerShell?

It’s always based on the conditional expression, these conditional expressions always return true or false, for example, if you want to check number comparison, if you want to check less than greater than and if you want to check type of variable (checking if variable if integer, string boolean or float) all these operations will return either true or false. In the below example we are checking if 5 is equal to 5 or not, so it is equal so it will print the message ‘Number is 5’.

Example:

If (5 -eq 5) {
'Number is 5'
}  Else {
'Number is not 5'
}

In below example, we are checking if 4 is equal to 5 or not, and the condition is false, hence it will print the message,’Number is not 5’

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,408 ratings)

If (4 -eq 5) {
'Number is 5'
}  Else {
'Number is not 5'
}

Output:

If Else in Powershell-1.1

Examples of If Else Statement in PowerShell

Below are the examples of If Else Statement in PowerShell:

Example #1

In this example, we are running a loop on numbers 1 to 10 and check if the number is less than 5 or equal to 5 or greater than 5. So here each time it compares the number with 5 if the condition expression inside the if block is true it will print the statement else it will check for the next if condition. And in the final, if none of the condition is true it will print the else block.

Code:

$Data = 1..10
$Data | ForEach {
If ([int]$_ -gt 5) {
"$($_) number is greater than  5"
} ElseIf  ([int]$_ -lt 5) {
"$($_) number is less than 5"
} ElseIf  ([int]$_ -eq 5) {
"$($_) number is equal to 5"
} Else  {
"Number is not identify"
}
}

Output:

If Else in Powershell-1.2

Example #2

In this example, we have marks of a student and we want to print a message about his/her marks. let see below example here we have students mark is 40 and we are checking his marks. So whichever condition of if expression gets the success it will print that if statement messages.

Code:

$studentMarks = 40
if($studentMarks -eq 30){
write-host("Value of student marks is 30")
} elseif($studentMarks -eq 40){
write-host("Value of student marks is 40")
} elseif($studentMarks -eq 50){
write-host("Value of student marks is 50")
} else {
write-host("Value of student marks is 60")
}

Output:

If Else in Powershell-1.3

Example #3

Let’s work with string operation, suppose we have one student and based on the match we wanted to display the message about student name. So if the student’s name is Ranja Display “Name of the student is Ranjan”.

Code:

$studentName = “Ranjan”
if($studentName -eq “Ajay”){
write-host("Name of student is Ajay")
} elseif($studentName -eq “Vijay”){
write-host("Name of student is Vijay")
} elseif($studentName -eq “Ranjan”){
write-host("Name of student is Ranjan")
} else {
write-host("IT LOOKS STUDENT DOES NOT BELONGS TO US")
}

Refer below the screen, here we assigned the student name as Ranjan, so when IF conditions get succeeded (ie. it matches the name) it will print that IF block else it will print ELSE block. You can try by assigning Ajay to $studentName and you can check the output.

Output:

output-1.4

Example #4

In this example, we are checking the student study graph, which means we are checking if the student is studying properly or not. So here we are assuming currently student marks is 200 and we are assuming that if marks are more than 200 than the student is hard-working if marks if equal to 200 than the student is ok and if marks are less than 200 it means the student is not studying properly.

Code:

$marks=200
if ($marks -gt 200) {
Write-Host("This student is very hard working.")
} elseif ($marks -eq 200) {
Write-Host ("This student is ok")
} else {
Write-Host ("This student is not studying properly")
}

Output:

output-1.5

Recommended Articles

This is a guide to If Else in PowerShell. Here we discuss how If Else Statement works in power Shell along with different examples and code implementation. You may also look at the following articles to learn more –

  1. Regex in PowerShell
  2. Parameters of PowerShell Move-Item
  3. PowerShell Remove-Item
  4. Comparison Operators in PowerShell
  5. Guide to Else If in C++with Examples
  6. Complete Guide to Else if in R with Examples
  7. Examples of IF ELSE Statement in SQL
  8. elseif in PHP | How to Works?
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ 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
1 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