PowerShell : Do-While & Do-Until Loop

Do-While & Do-Until Loop in PowerShell

Loops are an essential construct in any programming language as they enable a block of code to be repeatedly executed based on the condition. This can be useful for iterating through items in an object or repeatedly performing an operation. PowerShell supports involves setting a condition which either allows the loop to process as long as the condition is true or until it is met. 

  • The Do keyword works with the While keyword or the Until keyword to run the statements in a script block, up to the condition. The script block in a Do loop always runs at least once.
  • In a Do-While loop, the condition is evaluated after the script block has run. Then the while loop repeat the script until as long as the condition became false.
  • In a Do-Until loop always runs at least once before the condition is evaluated. However, the script block runs as long as the condition is false.

Do-While

Syntax : do {<statement list>} while (<condition>)

Example:

In below example, the loop will stop executing if condition became false that is if loop_index value reach 0 then condition became false.

$myArray = 1,2,3,0,4
do
{
$loop_index++;
}
while ($myArray[$loop_index] -ne 0)
$loop_index

Output:

3

Do-Until

Syntax : do {<statement list>} until (<condition>)

Example:

In below example, Do…Until loop is used when we want to repeat a set of statements as long as the condition is false.

$myArray = 1,2,3,0,4
do
{
$loop_index++;
}
until($myArray[$loop_index] -ne 0)
$loop_index

Output:

4

 

One thought on “PowerShell : Do-While & Do-Until Loop”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.