Coding Ref

PowerShell do-while loop

PowerShell do-while loop

In PowerShell, a do-while loop is a type of loop that repeats a block of code while a specified condition is $true.

This loop continues to execute the code block as long as the specified condition is $true, and it stops executing the code block when the condition becomes $false.

Example

Here's an example of a do-while loop:

$i = 0
do {
Write-Output $i
$i++
} while ($i -lt 10)

In this example, the do-while loop starts by initializing the $i variable to 0.

The code block inside the do-while loop contains the Write-Output cmdlet, which outputs the value of the $i variable to the console. The $i++ statement is used to increment the value of the $i variable by 1.

The while keyword specifies the condition that must be $true for the code block to continue executing.

In this example, the condition is ($i -lt 10), which means that the code block will continue to execute as long as the value of the $i variable is less than 10.

The do-while loop will output the numbers 0 through 9 to the console, and it will stop executing the code block when the value of the $i variable becomes 10 or greater.

Conclusion

A do-while loop is a useful tool in PowerShell for repeating a block of code while a specified condition is $true. It allows you to specify a condition and a code block, and it will execute the code block as long as the condition is $true.

You'll also like

Related tutorials curated for you

    How to get the date in PowerShell

    How to append content to a file in PowerShell

    What is read-host in PowerShell?

    How to sort and filter data in PowerShell

    How to find the Windows version from the PowerShell command line

    How to count objects in PowerShell

    What is IEX in PowerShell?

    What is a Scriptblock in PowerShell?

    How to get processes in PowerShell

    How to use If Else in PowerShell

    How to get the current directory in PowerShell

    What is WhatIf in PowerShell?