Strings

Microsoft® Windows® 2000 Scripting Guide

microsoft windows 2000 scripting guide

« Previous | Next »   

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

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

Properly Assigning String Data to a Variable


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