PowerShell tutorial. The While Statement

Similarly to the for statement, the while statement is another type of loop that parses through a collection. The while statement also includes a conditional code block and a script block and continues for so long as the conditional code block equal true.

Lets begin with an example;

$count =0
while ($count -lt 5)
"the count is

As you can see, the first line sets the $count variable equal to 0. This is because we are using it as a base starting value for the following loop. The following conditional code block ($count -lt 5) says that the$count variable must be less then 5. As long as the conditional code block equals true, the script block will be run. The first statement increases the value of the $count variable by 1. The second statement outputs a string that displays the value of the $count variable and continues until the conditional block equals 4.

the count is 1.
the count is 2.
the count is 3.
the count is 4.
the count is 5.

When $count is 4 the script block increments $count by 1 and displays the value of 5 through the output. When $count is 5 then the conditional block no longer equals true and the script.

Likely you will not always know the number of elements in a particular collection. In that case, you can still use the Count property to obtain that value.

$proc = Get-Process
$count = 0
while ($count -lt
"the " +
$proc[$count].name +
" process uses " +
$proc[$count].handles +
" handles."
$count ++

the script assigns the result of the Get-Process cmdlet to the $proc variable. This particular cmdlet returns a list of the processes running on the system. The conditional code block in the while loop specifies that the value in $count must be less than the total number of processes ($proc.count).

Leave a Reply