PowerShell primers

PowerShell for beginners: Scripts and loops

PowerShell primers

Show More
1 2 3 4 5 6 Page 5
Page 5 of 6

Do While

Do While is the simplest of the looping constructs in PowerShell. A looping construct is basically a piece of code that does the same action over and over to a set of things -- in other words, it loops through a set of things, doing something to each of them, until some condition changes or that set of things is exhausted.

There are two main types of looping constructs in PowerShell – -- a Do While loop, and another one I will explain in the next section.

Do While is simply a construct that says to PowerShell, "do this to this set of things until some condition I tell you becomes true." It's really as simple as that.

There are two ways to set up this construct. If you want a set of commands to execute at least once, and then as many times as are necessary to satisfy whatever condition you set up, you can simply put Do and a left curly brace on one line, the commands to execute starting on a new line after the left curly brace. And then on a new line, put the right curly brace followed by While and then, within parenthesis, your conditional statement. The conditional statement, again, must be true or false.

For example, let's set up a variable called numbers and give it an initial value of one.

$numbers = 1

Then, let’s set up a simple Do While construct that adds 1 to whatever number is already in that variable, until the variable has the number 10 in it.

Do {

$numbers = $numbers + 1

Write-Host "The current value of the variable is $numbers"

} While ($numbers –lt 10)

Here's what that looks like in the console:

PowerShell for Beginners

You can also set up a Do While construct so that your set of commands only executes when the condition is true. You just need to eliminate the do statement, and only use while.

While ($numbers –lt 10) {

$numbers = $numbers + 1

Write-Host "The current value of the variable is $numbers"

}

1 2 3 4 5 6 Page 5
Page 5 of 6
7 inconvenient truths about the hybrid work trend
Shop Tech Products at Amazon