PowerShell Loops Do


Example

Do-loops are useful when you always want to run a codeblock at least once. A Do-loop will evaluate the condition after executing the codeblock, unlike a while-loop which does it before executing the codeblock.

You can use do-loops in two ways:

  • Loop while the condition is true:

    Do {
        code_block
    } while (condition)
    
  • Loop until the condition is true, in other words, loop while the condition is false:

    Do {
        code_block
    } until (condition)
    

Real Examples:

$i = 0

Do {
    $i++
    "Number $i"
} while ($i -ne 3)

Do {
    $i++
    "Number $i"
} until ($i -eq 3)

Do-While and Do-Until are antonymous loops. If the code inside the same, the condition will be reversed. The example above illustrates this behaviour.