The While Statement
A language statement for running a command block based on the results of a conditional test
The while statement (also known as a while loop) is a language construct for creating a loop that runs commands in a command block as long as a conditional test evaluates to true. The while statement is easier to construct than a for statement because its syntax is less complicated. In addition, it's more flexible than the foreach statement because you specify a conditional test in the while statement to control how many times the loop runs.
The following shows the while statement syntax:
When you run a while statement, the Windows PowerShell evaluates the <condition> section of the statement before entering the <command_block> section. The condition portion of the statement resolves to either true or false. As long as the condition remains true, PowerShell reruns the <command_block> section.
The <command_block>} section of the statement contains one or more commands that are run each time the loop is entered or repeated.
For example, the following while statement displays the numbers 1 through 3 if the $val variable has not been created or has been created and initialized to 0.
In this example, the condition ($val is not equal to 3) is true while $val = 0, 1, 2. Each time through the loop, $val is incremented by 1 using the ++ unary increment operator ($val++). The last time through the loop, $val = 3. When $val equals 3 the condition statement evaluates to false and the loop exits.
To conveniently write this command at the PowerShell command-prompt, you can enter it in the following way:
Notice that the semi-colon separates the first command that adds one to $val from the second command that writes the value of $val to the console.
For information about performing boolean tests, enter the following command at the PowerShell command prompt:
For information about the foreach statement, enter the following command at the PowerShell command prompt:
For information about the for statement, enter the following command at the PowerShell command prompt: