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

Windows XP Under the Hood: An Introduction to VBScript

Brian Knittel introduces VBScript and its most important features.
This chapter is from the book

Introduction to VBScript

VBScript is the free version of Microsoft's Visual Basic programming language provided with Windows Script Host. It's virtually identical to Visual Basic for Applications, which is built in to many Microsoft applications for use as a scripting and "macro" language. Despite being somewhat stripped down from the full-price Visual Basic language, VBScript is fully capable of performing calculations, working with filenames and dates, and manipulating external objects. Although it can't display the complex dialog boxes, windows, and menus of a full-featured Windows application, it's powerful to serve the purpose of helping you manage your computer and automate day-to-day tasks. Although you could use many other languages to write scripts, VBScript is an excellent choice because you can transfer your experience in writing macros and programs for Word and Excel to Windows scripts, and vice versa.

In this chapter, I'll introduce you to VBScript and show you its most important features. I'll assume you have at least some familiarity with computer programming.

Programming concepts change little from one language to another, so if you have experience with any computer language, even if it was a one-day Word macro workshop or a class on FORTRAN using punched cards back in the 1970s, I think you'll pick up VBScript pretty quickly. Pay special attention to the illustrations called patterns. These are programming "building blocks" you'll find yourself using over and over.

After reading this chapter, you should visit the Microsoft Developer's Network at http://msdn.microsoft.com/scripting. This is the official VBScript Web site. It has the most current VBScript language reference online, which you can browse or download. There are articles, sample scripts, and add-ons you can download. Also, when new versions of Windows Script Host and VBScript are released, the announcements and download links will appear on this site.

The program examples in this chapter are brief, because they're designed to illustrate the basic commands and functions in VBScript. Meatier examples will follow in subsequent chapters.

I encourage you to test the scripts as written and also to modify them yourself, just to see what happens. For instructions on downloading and using the sample scripts, see www.helpwinxp.com/hood.

The first VBScript topics I'll cover are variables, and constants.


Variables hold the data you want to process. The data could be dates, times, numbers, or a series of arbitrary characters (commonly called a string). Strings are the most common type of data you'll work with, because your scripts will manipulate filenames, people's names, the contents of files, and other such information.

Variables are stored in the computer's memory and are accessed by a name. You refer to a variable by name to see or change its value. To assign a value to a variable, you use the = sign.

For example, consider the following lines of VBScript code:

FullName = "Sue Smith" 
Age = 40

When VBScript encounters these statements, it stores the string value "Sue Smith" in a variable called FullName, and the integer value 40 in the variable Age.

Several restrictions are placed on the names you can use for variables:

  • Names must begin with an alphabetic character and can contain only letters, numbers, and the underscore (_) character.
  • They cannot contain an embedded space, period, or other punctuation character. For example, big house and House.Big are invalid.
  • They must not exceed 255 characters in length.

Information can be placed into variables directly by your program (as in the Age = 40 example), it can be read in from files, or it can be derived or computed from other variables.

In most other programming languages, you have to define a variable's data type before using it—be it string, integer, object, date, or whatever. However, VBScript works the variable type out for itself, making life much simpler for the programmer as a result. In VBScript, all variables are of one fundamental data type called a variant. VBScript converts data from one type to another as needed. For example, if you attempt to "join" a variable containing a string to a variable containing a number, VBScript will convert the number to its text representation and then join the two strings together. If you add a number to a date, VBScript will add this number of days to the date, and so on.


In computer terminology, numbers and values that are typed into a program literally can be called, not surprisingly, literals, but they are most often called constants. The number 40 in the previous example is a constant. In fact, it's called a numeric constant because its value is...a number. VBScript lets you type in four types of constant values: Numeric, String, Date, and Boolean. Here's a rundown of all four types:

  • Numeric constant values are entered using digits and, optionally, a decimal point and/or a plus (+) or minus (-) sign indicator. Examples are 40, -20, and 3.14159. Don't insert commas in large numbers: For example, 1,234 is not allowed.
  • String constants are entered as text characters surrounded by quotation marks (""). Examples are "ABC" and "Now is the time". If you want to put a quotation mark inside the string, double it up. For example, "ABC""DEF" has the value ABC"DEF.
  • Date values are entered using the format Windows uses for your chosen locale (country), surrounded by pound signs. In the U.S., you could use #1/3/2002# to specify January 3, 2002. In most of the rest of the world this would be used to represent March 1, 2002. (VBScript uses the Locale setting you've made in the Windows Control Panel under Regional and Language Options to decide how to interpret this kind of date constant.)

    You can also use long date formats. For example, #January 3, 2001# and #3 January, 2001# are equally acceptable. If you don't mind typing things out like this, it's better to use a long date format because it's not subject to the regional ambiguity of the short format. Also note that if you specify a year with two digits, VBScript interprets 00 through 29 as 2000 through 2029, and 30 through 99 as 1930 through 1999. It's best to spell out years fully, though, so it's very clear to both you and VBScript what year you mean.

  • Time constants should be based on a 24-hour clock or should include text to indicate whether it is A.M. or P.M., as in #22:30:10# or #10:30:10 PM#.
  • You can also combine the date and time into one constant, as in #January 3, 2001 22:30:10#.
  • Boolean values can be entered as the words True and False.

Named Constants

Sometimes you'll write scripts with literal values that play an important role. For example, in a script that deletes all temporary files more than 30 days old, the number 30 will have to appear somewhere in your script, perhaps in several places. It might look something like this:

for each file in folder 
    if AgeOf(file) > 30 then file.Delete

Now, there's nothing magic about the number 30, and you might want to write your script in such a way that you can change this threshold later on without having to look for every occurrence of "30" in the script file. You could put the number 30 in a variable that you would use throughout the script:

MaximumAge = 30 


for each file in folder
    if AgeOf(file) > MaximumAge then file.Delete

The advantage of this is that you can set MaximumAge once at the beginning of the script and use the variable as many places as necessary. If you want to change the value, you only need to edit the first statement. Additionally, named values make the script easier to understand; they provide context that the numeric values don't.

However, variables are designed to, well, vary, and this particular value isn't intended to change while the script runs. So, like most programming languages, VBScript lets you define named constants that solve the literal value versus variable dilemma.

In VBScript, the statement

const MaximumAge = 30 

defines a value named MaximumAge, which you can use by name throughout the rest of your script, and which has the value 30. Named constants can be defined for any of the value types we discussed earlier: dates, times, numbers, and strings.

When you use a named constant in your scripts, you signal to anyone reading the script that the value is important and that it's fixed, and you get the benefit of defining it in one place while using it in many places. It's best to define all the constants you use in your script at the beginning of the script file so that they're easy to find.

When your script starts, several constants are already defined by VBScript. For example, the constants vbMonday, vbTuesday, and so on represent the days of the week, and you may use them when working with dates and times. I'll discuss some of the predefined constants in this chapter, and there's a complete summary of them in Appendix A. Now that we've covered how to specify variables and values, we can discuss how to manipulate them with operators and expressions.

Operators and Expressions

VBScript variables can be manipulated with operators to perform mathematical or character-string operations. For example, the + operator adds numeric variables. To compute Sue Smith's age next year, you could use this VBScript command:

age = age+1 

This means, take the variable age, add 1 to it, and store the result back in variable age.

When used with variables containing string values, the + operator concatenates the strings (joins them end to end). For example,

firstname = "Sue" 
lastname = "Smith"
fullname = firstname + " " + lastname

concatenates "Sue", a blank space (designated by the quotation marks), and "Smith" and then stores the result (Sue Smith) in the variable fullname.

In the previous example, I could also have written this:

fullname = firstname & " " & lastname 

VBScript lets you use the & character as an equivalent way to join strings. With strings, & and + do the same thing, but as a matter of good programming style, & makes it clearer to someone reading your program that strings are being added rather than numbers. Also, & has the added advantage that it can be used with variables and expressions of any type.

Operators are grouped into three categories:

  • Arithmetic operators. These include +, -, * (multiply), and / (divide).
  • Comparison operators. For example, > (is greater than) and <= (is less than or equal to).
  • Logical operators. For example, AND, OR, and NOT.

The comparison and logical operators produce neither a numeric nor string result, but rather a Boolean value (either True or False). These operators are used to direct the flow of control in a program, as in this example:

if Age > 40 then 
    write "You're not getting older, you're getting wiser"
end if

A combination of values and operators is called an expression. Here are some examples of expressions:


Value of Expression


The number 6

2 < 20

The Boolean value True

"A" & "B"

The string "AB"

Date() + 1

Tomorrow's date

Each of the operators in each category has a precedence, or priority, that determines the order in which the parts of the expression are calculated. The order of precedence within calculations does matter. For example, the value of the expression 1+3*3 is 10, not 12. Following the conventions used by mathematicians, multiplication has a higher precedence than addition. VBScript computes 3*3 first and then adds the result to 1. (Remember this discussion from high school algebra class?) You can use parentheses to force VBScript to evaluate expressions differently. For example, (1+3)*3 produces 12. Expressions in parentheses are computed first.

Sometimes expressions contain operators from more than one category. For example, the following comparison contains both an arithmetic and a comparison operator:

if A+B > C then ... 

In these situations, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear.

Tables 2.1 through 2.3 list all of the VBScript operators.

Table 2.1. Arithmetic Operators, from Highest to Lowest Precedence






Unary negation
















Integer division




Modulus (integer remainder)

9 mod 2











String concatenation

"abc" & "de"


The + operator also concatenates strings, but as I mentioned, it's best to get in the habit of using + for numbers and & for strings. Using & makes it more clear to someone reading your program that strings rather than numbers are being manipulated.

Table 2.2. Comparison Operators






Equal to

3 = 4



Not equal to

3 <> 4



Less than

3 < 4



Greater than

3 > 4



Less than or equal to

3 <= 4



Greater than or equal to

3 >= 4



Object equivalence

obj1 is obj2


The comparison operators are used mostly to let a script choose different actions, depending on the circumstances the script encounters. For example, a script can choose to delete a file if it's more than 24 hours old:

file_hours = DateDiff('h', file.DateLastModified, Now()) 
if file_hours > 24 then
end if

The first line determines how many hours have elapsed since the file in question was created or modified. Then, the comparison file_hours > 24 is True if file_hours is more than 24.

Table 2.3. Logical Operators, From Highest to Lowest Precedence







not (3 = 4)




(3 = 4) and (3 < 4)




(3 = 4) or (3 < 4)



Exclusion (different)

true xor true



Equivalence (same)

false eqv false



Implication (same or second value True)

false imp true


The logical operators are used to combine individual comparisons in order to address more complex situations, such as "If the file is more than 3 days old or the file is named anything.TMP, then delete the file."

If this is new territory, don't worry about all these operators right now. I'll use the more important ones in the examples throughout this chapter. For now, just remember that operators exist for every basic mathematical function, and you can refer back to these tables when you find the need.

Automatic Conversion

As mentioned earlier, when you combine variables or constant values of different types in one expression, VBScript tries to convert the values to appropriate types. Although it doesn't make sense to multiply a date by a number (what's two times August 4?), the addition and subtraction operators work in a surprisingly sensible way, as shown in Table 2.4.

Table 2.4. Automatic Conversions for Add and Subtract



Number + or - String

If the string represents a number, it is converted to a number and the result is a number. Otherwise, the program stops with an error message

Date/time + or - Number

Date. The whole (integer) part of the number is added to the date as a number of days. Any fractional part of the number is added as a time offset, as a fraction of a day (1 second = 0.0000115741; 12 hours = 0.5).

Date + or - String

If the string represents a number, it is converted to a number and the result is a date. Otherwise, an error occurs.

Anything & Anything

Values of any type are converted to strings and the strings are concatenated.

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.


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.


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.


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.


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


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


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.


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.


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