Home/PowerShell/PowerShell : Do-While & Do-Until Loop

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.

Output:

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.

Output:

 

Leave A Comment