Checking the Loop Condition

Microsoft® Windows® 2000 Scripting Guide

microsoft windows 2000 scripting guide

« Previous | Next »   

VBScript allows you to check the loop condition in one of two places: either before the loop begins or after the loop has concluded. This can make a difference in whether the loop is run. If you want to run the loop only if the condition has been met, check the condition before the loop is run. If you want ensure that the loop always runs at least one time, regardless of whether the condition has been met, check the condition after the loop has been run.

The following script sample illustrates the difference between the two methods for checking loop conditions. After setting a variable named LoopVariable to 1, the script sets up two loops. In the first loop, the condition is checked before the loop runs; this is done by using the following syntax:

Do Until LoopVariable = 1

The second loop uses this syntax, which does not check the condition until after the loop has been run:

Loop Until LoopVariable = 1

The script itself looks like this:

LoopVariable = 1 Do Until LoopVariable  = 1     Wscript.Echo "Script entered loop 1." Loop Do     Wscript.Echo "Script entered loop 2." Loop Until LoopVariable  = 1 

When the preceding script runs, the following output appears on the screen:

Script entered loop 2. 

As you can see, loop 2 ran a single time, while loop 1 did not run at all.

Why the difference? In the first loop, the condition (is LoopVariable equal to 1?) is tested before the loop begins. Because LoopVariable equals 1, the Do loop is skipped altogether.

In the second loop, however, the condition is not tested until after the loop has begun. Because scripts are processed sequentially, line by line, VBScript does the following:

  1. Sets up the Do loop.
  2. Echoes the message "Script entered loop 2."
  3. Checks to see whether the condition (is LoopVariable equal to 1?) is True. Because it is, the loop stops, but only after it has run one time.

With the Loop Until construct, the loop will always run at least one time. If that is not your intention, use the Do Until construct.


send us your feedback Send us your feedback « Previous | Next »   


Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 635

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net