Home » PowerShell While Loop

PowerShell While Loop

by Online Tutorials Library

While loop

In a PowerShell, the While loop is also known as a While statement. It is an entry-controlled loop. This loop executes the statements in a code of block when a specific condition evaluates to True. This loop is easier to construct than for statement because the syntax of this loop is less complicated.

Syntax of While loop

When we execute a while loop, PowerShell evaluates the condition first. Then, it executes the statements in a code of the block. The condition returns the Boolean value True or False. Until the Condition is ‘True‘, the PowerShell execute the statements repeatedly. When the Condition returns False, the loop will terminate, and the control goes to the statement after the loop.

Flowchart of While loop

PowerShell While loop

Examples

Example1: The following example prints the values from 1 to 5 using while loop:

Output:

1  2  3  4  5  

In this example, the condition ($count is less than equal to 5) is true while $count = 1, 2, 3, 4, 5. Each time through the loop, the value of a variable $count is incremented by 1 using the (+=) arithmetic assignment operator. When $count equals to 6, the condition statement evaluates to false, and the loop exits.

Example2: The following example finds the sum of first n natural numbers:

Output:

55  

In this example, the while loop is executed n number of times. And each time, the value of the variable $i is added to the $sum variable and values of $i is incremented by 1.

Example3: The following example prints the factorial of a number using while loop:

Output:

120  

You may also like