Home > Articles > Home & Office Computing > Microsoft Windows Vista & Home Server

This chapter is from the book

Flow Control

It's all well and good that you can assign values to variables and perform calculations, but the real power of programming is in the ability to perform operations over and over, and to take different actions when conditions require. That's where flow control comes in. Instead of just executing each and every line of a program in order from top to bottom, conditional statements let you specify how the program is to respond to various situations it may encounter. With looping statements, you can execute certain statements repeatedly. Looping statements record not only how to handle a repetitive task but how to know when to start and stop the task.

The If...Then Statement

The If...Then statement examines what is called a condition, and if the condition is true, it executes one or more VBScript statements.

Consider this example:

         ' Example File script0201.vbs 
if Hour(Time()) < 12 then
    MsgBox "It's morning, rise and shine!"
end if

A condition is an expression that can be examined and found to be either true or false. In the preceding example, the condition is Hour(Time()) < 12. Now, in VBScript, Time() represents the current time of day, and Hour(Time()) represents the current hour of the day—a number from 0 to 23. From midnight until just before noon, this number is indeed less than 12, so the condition Hour(Time()) < 12 will be true, and the script will display the "It's morning" message. From noon on, the hour is 12 or greater, so the message will not be displayed. Figure 2.1 shows what I saw when I ran this script one morning.

Figure 2.1

Figure 2.1 The Good Morning message is displayed when the hour of the day is less than 12.

If...Then statements can control your script's behavior based on any kind of condition that can be written with a combination of VBScript variables, operators, and functions and that ends up as a Boolean (true/false) value.

The If...Then statement has several variations that help you manage more complex situations. First of all, when there is only one command you want to use if the condition is true, you can put the entire statement on one line:

if Hour(Time()) < 12 then MsgBox "It's morning, rise and shine!" 

If you need to use more than one statement when the expression is true, you must use the If...End If version; Then followed by a line break starts a block of commands, and End If marks the end of the statements that are executed when the condition is true. Here's an example:

if Hour(Time()) < 12 then 
    MsgBox "Good Morning!"
    runreport "Today's Activities"
    DeleteTemporaryFiles
end if

In this example, if the script is run before noon, the if statement runs the three statements between if and end if.

If you want to perform some commands if the condition is true, but other commands if the condition is false, you can use the If...Then...Else version of the command:

if condition then 
    vbscript commands to perform
    when condition is true
else
    vbscript commands to perform
    when condition is false
end if

Only one set of commands or the other will be performed when the script is run. Here's an example:

         ' example file script0202.vbs 
if Hour(Time()) < 12 then
    MsgBox "Good morning"
else
    MsgBox "Good day"
end if

If there is just one command in the Else section, you can put the command on the same line as else and omit the end if. Here are the four possible arrangements:

if condition then 
    statements
    . . .
else
    statements
    . . .
end if

if condition then
    statements
    . . .
else statement

if condition then statement else   ' note that else must go here
    statements
    . . .
end if

if condition then statement else statement

Finally, sometimes you'll find that one Else isn't enough. Another variation of the If command uses an ElseIf statement. With ElseIf, you test multiple conditions with one long statement:

if condition then 
    vbscript commands go here
elseif othercondition then
    other vbscript commands here
elseif yetanothercondition
    yet more commands
else
     last set of commands
end if

Again, only one of the sets of VBScript commands will be performed—the commands belonging to the first condition that is true. If none of the conditions turn out to be true, the optional Else statement will be used.

If you use ElseIf, you cannot use the all-in-one-line format.

Note that If statements can also be nested one inside the other for more complex situations, as shown here:

if filetype = ".EXE " then 
    if filename = "WINWORD" then
        MsgBox "The file is the WINWORD.EXE program"
    else
        MsgBox "The file is some other program"
    end if
else
    MsgBox "This is some other type of file"
end if

Here, the "inner" If statement is executed only if the variable filetype is set to ".EXE".

The Select Case Statement

Suppose I have different commands I want to run depending on the day of the week. You know from the preceding section that I could use a series of If and ElseIf statements to run one section of VBScript code depending on the day of the week. For example, I can assign to variable DayNumber a numeric value (using the constants vbMonday, vbTuesday, and so on) corresponding to the day of the week. Then, I can use a long If statement to handle each possibility:

DayNumber = Weekday(Date()) 
if DayNumber = vbMonday then
    MsgBox "It's Monday, Football Night on TV "
elseif DayNumber = vbTuesday then
    MsgBox "Tuesday, Music lessons"
elseif DayNumber = vbWednesday then
    MsgBox "Wednesday, Go see a movie"
elseif DayNumber = vbThursday then
    ... (and so on)
end if

However, there's an easier way. When you find that you need to perform a set of commands based on which one of several specific values a single variable can have, the Select Case statement is more appropriate. Here's an example:

         ' example file script0203.vbs 
DayNumber = Weekday(Date())
select case DayNumber
    case vbMonday:    MsgBox "It's Monday, Football Night on TV"
    case vbTuesday:   MsgBox "Tuesday, Music lessons"
    case vbWednesday: MsgBox "Wednesday, Go see a movie"
    case vbThursday:  MsgBox "Thursday, fishing!"
    case vbFriday:    MsgBox "Friday, Party Time!"
    case else:        MsgBox "Relax, it's the weekend!"
end select

When the Select Case statement is run, VBScript looks at the value of DayNumber and runs just those commands after the one matching Case entry. You can put more than one command line after Case entries if you want, and even complex statements including If...Then and other flow-of-control constructions. You can also specify a Case Else entry to serve as a catchall, which is used when the value of the Select Case expression doesn't match any of the listed values. In the example, Case Else takes care of Sunday and Saturday.

Although it's powerful and elegant, Select Case can't handle every multiple-choice situation. It's limited to problems where the decision that controls the choice depends on matching a specific value, such as Daynumber = vbWednesday or Username = "Administrator".

If your decision depends on a range of values, if you can't easily list all the values that have to be matched, or if more than one variable is involved in making the decision, you'll have to use the If...Then technique.

Here are some other points about the Select Case statement:

  • Statements can follow case value: on the same line or on a separate line. VBScript permits you to write

    case somevalue: statement 
    

    or

    case somevalue: 
       statement
    

    I usually use the all-on-one-line format when all or most of the cases are followed by just one statement, as in the days of the week example I gave earlier. When the statements after the cases are more complex, I start the statements on a new line and indent them past the word case.

  • If one set of statements can handle several values, you can specify these values after the word case. For example, you can type case 1, 2, 3: followed by VBScript statements.
  • If more than one case statement lists the same value, VBScript does not generate an error message. The statements after the first matching case are executed, and any other matches are ignored.
  • You can use a variable or expression as the case value. Here's an example:
    somevalue = 3 
    select case variable
        case somevalue:
            statements
        case 1, 2:
            statements
        case else
            statements
    end select
    

If the value of variable is 3, the first case statements will be executed. If the variable can take on values that are listed as other cases, remember that only the first match will be used.

The Do While Loop

Many times you'll want to write a script where you don't know in advance how many items you'll have to process or how many times some action will need to be repeated. Looping statements let you handle these sorts of tasks. As a trivial example, the task of folding socks might be described in English this way:

as long as there are still socks in the laundry basket, 
   remove a pair of socks from the basket
   fold them up
   place them in the sock drawer
repeat the steps

In VBScript, we have the Do While statement to repeat a block of code over and over. In VBScript, the laundry-folding task might look like this:

do while NumberOfSocksLeft >= 2 
   MatchUpSocks
   FoldSocks
   PutSocksAway
   NumberOfSocksLeft = NumberOfSocksLeft - 2
loop

Here, the Do While part tells VBScript whether it's appropriate to run the statements following it, and Loop sends VBScript back to test the condition and try again. Do While statements can be nested inside each other, if necessary. Each Loop applies to the nearest Do While before it:

do while somecondition 
    ... statements
    do while SomeOtherCondition
       ... more statements
    loop
    ... still more stuff perhaps
loop

As you can see, indenting the program statements inside each Do While statement helps make this easy to read and follow.

There are actually five versions of the Do While loop, each subtly different:

do while condition 
    statements
loop

do until condition
    statements
loop

do
    statements
loop while condition

do
    statements
loop until condition

do
   statements
   if condition then exit do
   statements
loop

With the first version, VBScript evaluates the Boolean condition. If its value is True, VBScript executes the statement or statements inside the loop and goes back to repeat the test. It executes the set of statements repeatedly, every time it finds that condition is still True.

The second version loops again each time it finds that condition is False—that is, until condition becomes True. You could also write

do while not (condition) 
    statements
loop

and get the exact same result. Why have both versions? Sometimes you'll want to write "while there are more socks in the laundry basket" and sometimes you'll want to write "until the laundry basket is empty." The While and Until versions are provided so that you can use whichever one makes more intuitive sense to you.

Notice, though, that in these first two versions, if the While or Until condition fails before the first go-round, the statements inside will never be executed at all. In the second two versions, notice that the test is at the end of the loop, so the statements inside are always executed at least once.

The last version shows how you can end the loop from the inside. The exit do statement tells VBScript to stop running through the loop immediately; the script picks up with the next statement after the end of the loop. In this fifth version, the loop always executes at least once, and the only test for when to stop is somewhere in the middle. You can actually use exit do in any of the five variations of Do While. I'll discuss exit do more in the next section.

Every time you write a script using a Do While, you should stop for a moment and think which is the most appropriate version. How do you know which to use? You'll have to think it through for each particular script you write, but in general, here's the pattern to use:

Terminating a Loop with Exit Do

Sometimes it's desirable to get out of a Do While or other such loop based on results found in the middle of the statements inside, rather than at the beginning or end. In this case, the Exit Do statement can be used to immediately jump out of a loop, to the next command after the loop line.

For example, suppose you expect to be able to process five files, named FILE1.DAT, FILE2.DAT, and so on. However, if you find that a given file doesn't exist, you might want to stop processing altogether and not continue looking for higher numbered files. The following shows how you might write this up in a script:

set fso = CreateObject("Scripting.FileSystemObject") 
num = 1
do while num <= 5                              ' process files 1 to 5:
    filename = "C:\TEMP\FILE" & num & ".DAT"   ' construct filename
    if not fso.FileExists(filename) then       ' see file exists
        exit do                                ' it doesn't, so terminate early
    end if
    Process filename                           ' call subroutine "process"
    num = num + 1                              ' go on to next file
loop

In this example, the first time through the loop, we set variable filename to FILE1.DAT. Each turn through increments variable num by one. We test to be sure the file whose name is stored in variable filename really exists. If the file does not exist, Exit Do takes the program out of the loop before it attempts to process a missing file.

There's no reason we have to limit the Do While loop to a fixed number of turns. If we omit the "do" test entirely, it will run forever. The constant True is just what it sounds like, so we could rewrite the previous script to process as many files as can be found, from 1 to whatever:

         ' example file script0204.vbs 
set fso = CreateObject("Scripting.FileSystemObject")
num = 1
do                                  ' process as many files as found
   filename = "C:\TEMP\FILE" & num & ".DAT"    ' construct filename
   if not fso.FileExists(filename) then        ' see file exists
      exit do                                  ' no, terminate early
   end if
   Process filename                            ' call subroutine "process"
   num = num + 1                               ' go on to next file
loop

Here, without a While or Until clause, the loop runs indefinitely (it's what programmers call an infinite loop), until Exit Do ends it. This means that you have to be careful that Exit Do eventually does get executed; otherwise, your script will churn through the loop forever (or until your patience runs out and you cancel it by typing Ctrl+C).

The Exit Do statement works in any of the four variations of Do While and Do Until statements.

Counting with the For...Next Statement

When a loop needs to run through a set number of iterations, the For...Next statement is usually a better choice than the Do While statement. The first example I used for Exit Do can be rewritten as a For loop like this:

         ' example file script0205.vbs 
set fso = CreateObject("Scripting.FileSystemObject")
for num = 1 to 5                                  ' process files 1 to 5:
     filename = "C:\TEMP\FILE" & num & ".DAT"     ' construct filename
     if not fso.FileExists(filename) then         ' see file exists
         exit for                                 ' no, terminate early
     end if
     Process filename                             ' call subroutine "process"
next

The For loop sets a variable (num, in this example) to the first value (here, 1) and processes the statements inside. It then increments the variable and repeats the statements until the variable is larger than the number after To (here, 5). This loop thus processes the statements with num = 1, 2, 3, 4 and 5.

In the example, I also used the Exit For statement, which works exactly like Exit Do, except that it breaks out of a For loop rather than a Do loop. (Makes sense, doesn't it?!) The Exit For statement makes VBScript continue processing the script with the line after Next.

The For statement can be written in either of two ways:

for counter = startvalue to endvalue 

or

for counter = startvalue to endvalue step stepvalue 

Here, counter is the variable to be used; startvalue is the value that the variable is to take the first time through the loop; endvalue is the largest value the variable is to take; and stepvalue, if specified, is the value by which to increment counter each time through. The stepvalue can be negative if you want your loop to count backward, as in this rendition of a well-known, irritating song:

         ' example file script0206.vbs 
for number_of_bottles = 100 to 0 step -1
     wscript.echo number_of_bottles & " bottles of beer on the wall!"
next

If the Step clause is left out, the counter variable is incremented by one each time.

Processing Collections and Arrays with For...Each

Some special-purpose VBScript functions can return a variable type called a collection. A collection is a list of filenames, usernames, or other data contained in a single variable. For example, a directory-searching function might return a collection of filenames when you ask for all files named *.DOC. Because you'll probably want to print, view, or manipulate these files, you need a way of accessing the individual items in the collection.

The For...Each loop runs through the loop once for each item in a collection. Here's an example:

         ' example file script0207.vbs 
set fso = CreateObject("Scripting.FileSystemObject")
set tempfiles = fso.GetFolder("C:\TEMP").Files

filelist = ""
for each file in tempfiles
    filelist = filelist & ", " & file.name
next

MsgBox "The temp files are:" & filelist

In this example, the variable tempfiles is set to a collection of all the files found in folder C:\TEMP. The For...Each loop creates a variable named file, and each time through the loop it makes variable file refer the next object in the collection. The loop runs once for each file. If the collection is empty—that is, if no files are included in folder C:\TEMP—then the loop doesn't run at all. You also can use the For...Each statement with array variables, executing the contents of the loop once for each element of an array, as shown in this example:

dim names[10] 
...
for each nm in names
    ...
next

The VBScript statements inside this loop will be executed 10 times, with variable nm taking one each of the 10 values stored in names in turn.

To learn more about arrays, see "Arrays," p. 79.

You can use any variable name you want after for each; I chose names file and nm in the examples because they seemed appropriate. You can use any valid variable name you wish.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020