Windows XP Under the Hood: An Introduction to VBScript
- Introduction to VBScript
- Flow Control
- VBScript Functions
- Interacting with the User
- Advanced VBScript Topics
- Where to Go from Here
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
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.
Constants
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 next
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 next
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:
Expression |
Value of Expression |
3+3 |
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
Operator |
Meaning |
Example |
Result |
- |
Unary negation |
-5 |
-5 |
^ |
Exponentiation |
2^5 |
32 |
* |
Multiplication |
2*3 |
6 |
/ |
Division |
9/2 |
4.5 |
\ |
Integer division |
9\2 |
4 |
mod |
Modulus (integer remainder) |
9 mod 2 |
1 |
+ |
Addition |
3+5 |
8 |
- |
Subtraction |
8-5 |
3 |
& |
String concatenation |
"abc" & "de" |
"abcde" |
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
Operator |
Meaning |
Example |
Result |
= |
Equal to |
3 = 4 |
False |
<> |
Not equal to |
3 <> 4 |
True |
< |
Less than |
3 < 4 |
True |
> |
Greater than |
3 > 4 |
False |
<= |
Less than or equal to |
3 <= 4 |
True |
>= |
Greater than or equal to |
3 >= 4 |
False |
is |
Object equivalence |
obj1 is obj2 |
False |
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 file.Delete 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
Operator |
Meaning |
Example |
Result |
not |
Negation |
not (3 = 4) |
True |
and |
Conjunction |
(3 = 4) and (3 < 4) |
False |
or |
Disjunction |
(3 = 4) or (3 < 4) |
True |
xor |
Exclusion (different) |
true xor true |
False |
eqv |
Equivalence (same) |
false eqv false |
True |
imp |
Implication (same or second value True) |
false imp true |
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
Operation |
Result |
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. |