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 do while
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

PowerShell do while

PowerShell do while

Introduction to PowerShell do while

The do-While loop in PowerShell is one of the iterative loops (for, foreach, while, do-while) that runs the content inside the block multiple times based on the condition provided, runs until the condition is true, and terminates when the condition becomes false, moreover it ensures that the loop will execute at least once and this loop is opposite of the Do-Until loop which runs until the condition is True and stops when the condition becomes false. Most of the times conditions are checked with the conditional operators.

Syntax

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Do-While loop syntax

do {
Statement 1
Statement 2
............
............
Statement N
} while (condition)
Do-Until loop syntax
do {
Statement 1
Statement 2
............
............
Statement N
} until (condition)

Flowchart

Flow chart for the Do-While loop.

<image>

How do-while loop works in PowerShell?

 Do-While loop ensures that the loop will be executed at least once by entering the loop the first time and then later it checks the condition and enters into the loop if the condition is True or vice versa.  For example,

do {
Write-Output "`nThis loop is Guaranteed to execute the first time"
} while ($false)

Output:

PowerShell do while output 1

If you see the above output, the loop is executed even the condition is false because it is by its design that it enters into the loop first, and then for the next run it checks the While condition until it becomes false.

If we use $true in the condition, the loop will become infinite and it will never terminate because the condition will never become false.

On the contrary, the opposite loop do-until executes until the condition becomes true. For example,

do {
Write-Output "`nUntil is Guaranteed to execute first time"
} until ($true)

Output:

PowerShell do while output 2

If we have used $false condition here, the loop will never be exited because the condition inside the while will never become false.

Difference between While, Do-While loop and Do-Until loop.

While Loop:

$a = 100
While ($a -gt 110) {
$a++
Write-Output "This won't be printed"
}

In the above example of while loop, the output won’t be printed

Do-While Loop:

$a = 100
do {
$a++
Write-Host "`nThis line will be printed once only" -BackgroundColor DarkGreen
} while ($a -gt 110)

Output:

PowerShell do while output 3

In the above example, the output will be printed once only because the condition becomes false.

Do-Until Loop:

$a = 100
do {
$a++
Write-Host "`nThis line will be printed 10 times" -BackgroundColor DarkGreen
} until ($a -gt 110)

Output:

PowerShell do while output 4

Examples

Here are the following examples mention below

Example #1 – Simple Do-While loop.

$i = 0
do {
$i
$i++
} while ($i -lt 5)

Output:

PowerShell do while output 5

In the above example, the $i variable is initialized with 0 and inside the do-while loop the value increments by one at every iteration, and the loop terminates when the $i value reaches 5.

Example #2 – Do-While loop with multiple conditions.

$i = 0
$j = 0
do {
Write-Output "i = $i, j= $j"
$i++
$j = $j + 2
} While(($i -lt 5) -and ($j -lt 15))

Output:

output 6

In the above example, if any of the conditions becomes false, the loop terminates.

See the another example with multiple conditions.

$i = 0
$j = 0
do {
Write-Output "i = $i, j= $j"
$i++
$j = $j + 2
} While(($i -lt 5) -or ($j -lt 15))

Output:

output 7

In the above example, if both of the conditions become false then the loop is terminated and for any single true condition, it enters into the loop.

Example #3 – Do-While loop with an array.

We can iterate through each array items with Do-While loop. In the below example,

$animals = @("Cow","Dog","Cat","Elephant")
$i = 0
do{
$animals[$i] $i++
}while($i -lt $animals.Length)

Output:

output 8

In this example, each item under the Animals array is printed because the $i value starts from 0 and continues until the length of the Animal array.

Example #4 – Do-While loop with Break

We can terminate the Do-While loop using the Break statement. In this example, we need if the value of the array meets the specific value then the loop should be terminated. An example is shown below.

$i = 0
do {
$i
$i = $i + 2
if($i -eq 10){ break }
} while ($i -lt 20)

Output:

output 9

When the $i value becomes 10, the do-while loop is terminated automatically.

Example #5 – Do-While loop with Continue

To skip the particular iteration, the Continue keyword is used. We can use the Continue keyword with the Do-While loop as shown below.

$i = 0
do{
if($i -eq 10) {
$i = $i + 2
Continue
}
$i
$i = $i + 2
}while($i -lt 20)

Output:

output 10

In the above example, when the $i value becomes 10, next all the commands will be skipped during that iteration so here the output 10 isn’t displayed.

Example #6 – Do-While loop with User Input prompt.

Sometimes we need the input values from the User and we need to continue until the user enters the correct input. You can use the Do-While loop for that. For example,

$choice = ""
do{
Write-Output "*********************************"
Write-Output "`tPress 'R' to Restart VM"
Write-Output "`tPress 'S' to Shutdown VM"
Write-Output "*********************************"
$choice = Read-Host 'Enter Choice '
switch($choice){
'r'  { "Reboot selected"}
's' {"Shutdown selected"}
}
}while(($choice -ne 'r') -and ($choice -ne 's'))

The above script will prompt for the user input and continues until the $choice value doesn’t become ‘R’ or ‘S’.

Output:

output 11

Conclusion

Like any other loop function (For, Foreach, While), the Do-While loop is also very helpful in PowerShell or various scripting languages. You can use this loop for various programs where you need the loop needs at least one-time execution and later checks the condition. For example, you can use the Test-WSMan command after server reboot inside this loop to check if the WINRM connectivity is established or not.

Recommended Articles

This is a guide to PowerShell do while. Here we discuss How do-while loop works in PowerShell along with the examples and outputs. You may also have a look at the following articles to learn more –

  1. PowerShell Match
  2. PowerShell Boolean
  3. PowerShell Wait
  4. PowerShell SubString
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
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

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

EDUCBA

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

Let’s Get Started

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
EDUCBA

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

Forgot Password?

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