PowerShell Tutorial – Loops (For, ForEach, While, Do-While, Do-Until)

  1. init-expr – This normally initializes one or more counters to be used in the loop.
  2. eval-expr – This evaluates a condition, if the condition is true the code block is the loop is executed, if false then the loop is exited.
  3. increment-expr – This determines how much the increment is on each completion of a loop.

The below For Loop example, shows how to use a For Loop to generate a multiplication table for the number 6 for all values between 1 and 10. The loop starts with value 1, evaluates the value, and then determines whether it is less than 10. The loop continues until the condition (  $i -lt 10 ) is true and increments the value by 1 on each loop:

$testvar=6
for ($i = 1; $i -lt 10; $i++)
{write-host $i "X" $testvar "=" ($testvar*$i)}

While Loop

The only  difference between a For loop and a While loop is that in the While loop the value is initialized before the loop. The While loop is a very simple construct it doesn’t initialize or increment any fields automatically, it simply tests a condition and then executes the loop for as long as the condition remains true.  In the While loop, the evaluation and the incremental part of the code are inside the loop as an expression:

$testvar=6
$i = 1
while ($i -le 10)
{ write-host $i "X" $testvar "=" ($testvar*$i) ;$i++}

Do-While Loop

The Do-While loop consists of a code block and a condition. First the code within the block is executed, and then the condition is evaluated. If the condition is true, the code within the block is again executed and the loop  continues until the condition is false. The only difference with the While loop is that the evaluation is after the code block so the loop always executes at least once.

$testvar=6
$i = 0
do { write-host $i "X" $testvar "=" ($testvar*$i) ;$i++}
while ($i -le 10)

Do-Until Loop

Similar to the Do-While loop, the Do-Until loop construct consists of a block of code and a condition. The code block is executed first  and then the condition is evaluated. The only difference is the loop is executed if the statement evaluates to false. In practice Do-Until loops are rarely used as the Do-While loop can perform exactly the same operation is the statement is rewritten.

$testvar=6
$i = 0
do { write-host $i "X" $testvar "=" ($testvar*$i) ;$i++}
until ($i -eq 11)

One thought on “PowerShell Tutorial – Loops (For, ForEach, While, Do-While, Do-Until)

  1. Pingback: PowerShell Tutorial – CmdLets | Windows Server Help

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>