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 Statement 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 Statement in PowerShell

By Priya PedamkarPriya Pedamkar

If Statement in PowerShell

Introduction to If Statement in PowerShell

The If Statement in PowerShell allows the programmer to control the flow of execution of the program, the” IF” statement defines if a program has to execute a section of code or not, based on whether a given condition expression is correct or not. Here correct in programming terms true or false. One of the main uses of if statement allows the program to make the decision on the basis of one or more conditions.

And if a statement is based on the boolean value, if the boolean condition value is true than inside the if block and execute the lines of statements inside if block. In another simple word, To execute any statements it has to test one or multiple conditions if conditions are true it will execute the statement. “If” statement needed when we wanted to check any specific case.

Introduction to If Statement in PowerShell

What is PowerShell?

PowerShell is a way to write Administrative commands on Windows environments, it is similar to bash scripting in Linux. It provides a way to automate the Windows operating system and its applications to deal with various tasks.PowerShell is available for both Windows and Linux operating systems, but in this tutorial, we are focusing on windows. In the below image we can see how Powershell controls all Automation works.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

Syntax of if in PowerShell is very much similar to other programming languages. It checks for the condition if the condition expression is true it will be got to if block if the condition expression is false it will go to else.

if(condition) {
// Executes when the condition is true
}else {
// Executes when the condition is false
}

We can also use elseif, syntax below.

if(condition 1) {
// Executes when the condition 1 is true
}elseif(condition 2) {
// Executes when the condition 2 is true
}elseif(condition 3) {
// Executes when the condition 3 is true
}else {
// Executes none of the condition is true.
}

Flow diagram

Flow diagram

In the below flow diagram we can see when execution starts, it first checks the condition. If the condition is true then it will go to the statement block. Here conditions can be one or multiple. Any condition other than zero, false, blank are considered as true only .for example if any conditional expression gives an output of 0,”, false all these are considered as false statements.

How does if statement work in PowerShell works?

if (<cond1>)
{<statement1>}
[elseif (<cond2>)
{<statement2>}] [else
{<statement3>}]

Here, when it starts execution it checks for cond1 as if it is true or false, based on the value it will execute the statement block if cond1 is true it will execute statement1 and PowerShell exit. But if cond1 is false, then it will check else if block cond2, if cond2 is true then statement2 will be executed. If cond1 and cond2 both are false or none of the condition is true then else statement will be executed.

The condition can be one or multiple, for example.

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 (<condition 1 -or condition 2>)
{<statement1>}
[elseif (<condition 3 -or condition 4>)
{<statement2>}] [else
{<statement3>}]

Examples for If Statement in PowerShell

The examples of If Statement in PowerShell is given below:

Example #1 – Simple if-else example

Code:

$x = 40
if($x -le 20){
write-host("value of x is less than 20")
}else{
write-host(“value of x is greater than 20”)
}

Output:

if statement in powershell for Examples 1

Explanation: The above code is checking the value of $x, if it is less than 20 or not, if the value of $x is less than 20 it will execute if the statement block.

Example #2 – with Multiple conditions

Code:

$day = (get-date).dayofweek
if(($day -ne "Saturday") -or ($day -ne "Sunday")){
write-host("Welcome to Our Banks")
}else{
write-host(“Hello friends , Banks are closed today”)
}

Output:

if statement in powershell for Examples- Multiple conditions

Explanation:

The above code will print output according to today. Here it matches case the value of $day, so if a day is Sunday or Saturday, it will print  “Hello friends, Banks are closed today” and if it’s other than Sunday and Saturday it will print “Welcome to Our Banks”.

Example #3 – if-else if conditions

Code:

$occupation =”engineering”
if($occupation -eq "engineering"){
write-host("engineer")
}elseif($occupation -eq "sales"){
write-host("sales")
}else{
write-host("accounting")
}

Output:

 if-else if conditions

Explanation:

In the above code, it checks for $occupation value, if it is equal to engineering than print engineering if the value if $occupation is sales then it will print sales, and if $occupation is none then it will print accounting.

Example #4 – Functional Based

Code:

function check ($VALUE) {
if ($VALUE) {
Write-Host(“TRUE”)
} else {
Write-Host(“FALSE”)
}
}
check $FALSE
check $TRUE
check FALSE //FALSE is a String with length > 0
check TRUE //TRUE is a string length >0

Output:

Functional Based 

Note: In PowerShell String with length, more than zero is considered as true.

Explanation:

In the above example first, it calls for check function with parameter  $TRUE, and inside function check, it checks for $VALUE and if it is true it will print TRUE, in a similar way again check-called with parameter $FALSE and it check $VALUE and as it is false it will go to the else block.

Let me explain to you some real use cases where we needed “if”.

If we want to check if the database server is up or down(checking if the database is running or not) then we can use if statement. So if the database is down then run any service or command to up database. This will be completely automated which will check all the time database status.

Code:

$x = Dbconnection()//$x is true or false
if($x){
write-host("Start database services process")
//run some script to handle a situation
}

Many times because of the heavy load on a server it stops working, so to check the threshold load capacity of the server we can use Powershell if condition and inside condition we can write our required statements.

Code:

$x = loadValue()//200000 is threshold load capacity
if($x -le 200000){
write-host("Load is ok")
}else{
write-host("Load is exceed threshold capacity")
//write conditions for handling conditions .
}

With the above example, we are clear that if a statement can play a very crucial role in the real software world.

Recommended Articles

This is a guide to If Statement in PowerShell. PowerShell IF is a very powerful tool to handle conditional statements Here we discuss what is PowerShell? how does if statement works in PowerShell? along with respective examples and flow chart. You can also go through our other related articles to learn more–

  1. If Else in PowerShell
  2. Hashtable in PowerShell
  3. Powershell Write-Host
  4. PowerShell Run Command
  5. Complete Guide to Else If in C++
  6. Methods and Constructor of Hashtable in Java
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ 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