Concatenating Strings

Microsoft® Windows® 2000 Scripting Guide

Concatenation is the process of combining two or more strings into a single string. (You can also combine strings with numeric or date values.) Concatenation is often used to provide more readable or more meaningful output. For example, the script in Listing 2.4 returns the value 10340. This is very useful information, provided you know that the script is designed to return the number of megabytes of free disk space on drive C. But if you do not know what the script is designed to do, that output will be meaningless.

Among other things, concatenation helps you provide context for your script output. For example, rather than displaying the value 10340, you might want to display a message similar to "There are 10340 megabytes of free disk space." To do this, you must combine the following three items:

"There are " a simple string representing the start of the message.

FreeMegabytes the variable containing the number of free megabytes on the drive.

" megabytes of free disk space." a second string representing the end of the message.

As shown in lines 6 and 7 of Listing 2.7, you concatenate items in VBScript by using the ampersand (&).

The underscore (_) at the end of line 6 is known as the line continuation character and is used to indicate a statement break. This means that lines 6 and 7 should be treated as one line; the line was simply too long to fit in the allotted space. Statement breaks are covered in more detail later in this chapter.

Alternatively, you might have assigned the value "There are " to a variable named MessageStart and the value "megabytes of free disk space." to a variable named MessageEnd. You could then have concatenated the three variables like this:

If you look closely at lines 6 and 7, you will notice that blank spaces were hard-coded into the string values "There are " and " megabytes of free disk space." This is required because the ampersand does not insert any spaces between the items being concatenated. For example, suppose you leave out the blank spaces, like this: