Converting VBScript's For...Next Statement

Windows PowerShell

Definition: Repeats a group of statements a specified number of times.


A For Each loop is designed to run a block of code against each and every item in a collection; by contrast, a For Next loop is typically designed to run a specific number of times. For example, to run a code block 10 times you might set up a loop that begins with a counter variable set to 1. Each time through the loop the counter variable is incremented by1, and the loop ends only after that counter variable is equal to 10.

In other words, something similar to this:

for ($a = 1; $a -le 10; $a++) {$a}

In this command we use the For keyword followed by two items: the loop condition (enclosed in parentheses) and the code we want to execute each time we run through the loop (enclosed in curly braces). The loop condition requires three values:

  • The starting value. We want our loop to run from 1 to 10, so we set a counter variable named $a equal to 1.

  • The ending value. We want the loop to run 10 times, so we specify that the loop should continue as long as $a is less than or equal to 10. If and when the value of $a becomes greater than 10 the loop automatically ends.

  • The “incrementer.” Each time through the loop we want the value of $a to increase by 1; therefore we use the ++ operator. Suppose we wanted to increment $a by 2 each time through the loop (equivalent to Step 2 in a VBScript loop). In that case we would use this syntax: $a+=2, which adds 2 to the current value of $a.

As to the code we want to run each time through the loop, well, here we’re keeping it pretty simple; we’re just echoing back the current value of $a:


Here’s what we’ll get back when we execute this command:


Return to the VBScript to Windows PowerShell home page