Microsoft® Windows® 2000 Scripting Guide
As you write more sophisticated scripts, you will begin to encounter different types of data (a topic covered in more detail later in this chapter). In line 1 of Listing 2.5, for example, numeric data was used to assign the literal value 1048576 to the constant CONVERSION_FACTOR:
Const CONVERSION_FACTOR = 1048576
This line of code works because a numeric value is being assigned to the constant. Anytime you assign a numeric value to a variable or a constant, you simply type the equals sign followed by the value.
However, unexpected results occur if you try to assign an alphanumeric value (typically referred to as a string value) using this same approach. For example, the following code sample attempts to assign the string atl-dc-01 to the variable Computer and then echo the value of that variable:
Computer = atl-dc-01 Wscript.Echo Computer
When this script runs, however, the dialog box shown in Figure 2.4 appears.
Figure 2.4 Improperly Assigning String Data to a Variable
How did the value 1 get assigned to the variable Computer? When VBScript encounters a set of alphanumeric characters that is not surrounded by quotation marks, it assumes that these characters represent the name of a variable. If it sees a "stray" hyphen, it assumes that the hyphen represents a minus sign. As a result, VBScript interprets the line Computer = atl-dc-01 as "The variable Computer is to be assigned the value of the variable atl minus the value of the variable dc minus 01." Because atl and dc are viewed as new variables that have not been initialized, they are assigned the value 0. VBScript thus interprets this line of code as if it were written like this:
Computer = 0 - 0 - 1
As a result, the variable Computer receives the erroneous assignment 1.
When you assign a string value to a variable or a constant, you must enclose that value within quotation marks; this is the only way to ensure that VBScript treats the string as an alphanumeric value and not as a variable. For example, the following code sample correctly assigns the string atl-dc-01 to the variable Computer and then echoes the results:
Computer = "atl-dc-01" Wscript.Echo Computer
When this script runs, the dialog box shown in Figure 2.5 appears.
Figure 2.5 Properly Assigning String Data to a Variable