EDUCBA

EDUCBA

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

PowerShell While Loop

By Chirag NagarekarChirag Nagarekar

PowerShell While Loop

Introduction to PowerShell While Loop

While loop in PowerShell is an iterative loop, which runs until the condition satisfies. You can write multiple lines of code inside the while block and run it several times until the criteria met. It is like FOR loop but the structure is different.

Diagram:

Diagram powershell

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

While (condition) {
Operation commands
}

Parameters:

  • Condition: Conditional parameter is specified here. This condition may be one or more and output will be in the Boolean format ($True or $False). While loop runs based on this condition, and once the condition is false, the loop is terminated automatically.
  • Operation Commands: These commands can be simple or complex commands. It runs every time when the condition is satisfied.

The above syntax is equivalent to,

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

while (true) {
if (!condition)
break;
statements;
}

How PowerShell While Loop Works?

During the While block in PowerShell, first of all, initialization of variables and other parameters happen and then there is a condition check. The condition can be one or more and based on the condition if it becomes true then it executes the Body function, again it repeats the check after executing the body part and if the condition is satisfied again then it again executes the body part. This same process repeats until the condition becomes false. Once the condition is false, the loop is terminated.

If the condition is false at the beginning then the script will not go inside the body function but remember to specify a condition or command that can make loop terminated eventually otherwise the loop will be executed forever. You can also terminate the execution of a block with the BREAK command when the specific criteria met or skip the current iteration using the CONTINUE statement.

Examples of PowerShell While Loop

Let us see some of the examples of while loop in PowerShell which are given below:

Example #1 – Using Simple While Loop

Below script will first initialize the variable $i=1 and executes while loop. Here the condition $i value 1 is less than equal to 10, so it enters into the body statement and executes Write-Output command and then increments the value of $i to 2 and then again checks the condition and enters into a loop. The same process works until the $i value reaches 11 and the condition gets false and the loop is terminated. If you don’t put $i++ then loop executes forever as it script can’t find any termination condition.

Code:

$i=1
while($i -le 10){
Write-Output "Value of i : $i"
$i++
}

Output:

While Loop in PowerShell eg1

Example #2 – Multiple Conditions with –AND Operator

Code:

$i=5
$j=10
while(($i -le 10) -and ($j -ge 7) ){
Write-Output "Value of i : $i"
Write-Output "`nValue of j : $j"
$i++
$j--
}

Output:

While Loop in PowerShell eg2

In the above example, if any of the conditions get false (When $i value becomes greater than 10 and $j value becomes less than 7) then loop terminates. Here, a value of $j first reaches to 6 and it can’t satisfy the while loop condition and the loop gets terminated.

Example #3 – Multiple Conditions with -OR Operator

Code:

$i=5
$j=10
while(($i -le 10) -or ($j -ge 7) ){
Write-Output "Value of i : $i"
Write-Output "`nValue of j : $j"
$i++
$j--
}

Output:

While Loop in PowerShell eg3

Here, in –OR condition, if any of the two statements satisfy then the loop gets executed.

Example #4 – Condition Inside the While Loop

Like normal function, you can specify conditions inside the while loop.

Code:

$i=5
while($i -ge 10){
if($i -eq 8){
Write-Output "Variable value reached to 8"
}
$i++
}

Output:

While Loop in PowerShell eg4

Example #5 – While Loop with Break Statement

As shown in the above example, the loop executes until the while condition satisfies but if we want a loop to be terminated when if condition met then we need to use the Break command. Once the break command is executed it terminates all the loops (Parent and Child).

Code:

$i=5
while($i -le 10){
if($i -eq 8){
Write-Output "Break command is going to run now"
Break
}
Write-Output "After break this will not executed"
$i++
}

Output:

eg5

In the above example, when the variable value becomes 8 in the IF statement, then IF block executes and break is also executed and the entire loop is terminated. You can see the difference in the above two examples.

Example #6 – While Loop with Continue Statement

When the CONTINUE statement is executed, it skips the current loop and returns to the main loop. In the below example, when the value reaches 8, it skips the rest of the program and returns to the main WHILE loop.

Code:

$i=5
while($i -le 10){
$i++
if($i -eq 8){Continue}
Write-Output $i
}

Output:

eg6

Example #7 – Nested While Loop

You can also use the nested WHILE loop. See the example below.

Code:

$i=0
$j=0
while($i -lt 3){
While($j -lt 3){
Write-Output "`ni = $i"
Write-Output "j = $j"
$j++
}
$i++
$j=0
}

Output:

eg7

In this example, the first main while loop is executed for the $i value of 0 and then the script executes full inner while loop. Again for the $i=1, the script executes the inner while loop and it continues until the value of $i meets the condition.

Example #8 – While Loop with $TRUE

You can also structure while loop as below.

Code:

$i = 5
while($true){
Write-Output $i
if($i -eq 8){Break}
$i++
}

Output:

eg8

In the above example, while loop executes forever because of the $true is specified in the condition. To terminate the loop, use the Break command when condition satisfies.

Conclusion

While loop has the same functionality as the other loops as FOR, FOREACH, and Do-While. In the Do-While loop, the body statement is executed first and the condition is checked later.

Recommended Articles

This is a guide to PowerShell While Loop. Here we discuss the syntax and working of PowerShell While Loop along with examples and code implementation. You may also have a look at the following articles to learn more –

  1. Tools of PowerShell
  2. Syntax and Parameters of PowerShell Sort-Object
  3. Examples of Logical Operators in PowerShell
  4. How does Hashtable work in PowerShell?
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