[Previous] [Table of Contents] [Next]

# Creating and Using Scripts

Are you ready to create and use your first script? To begin, we'll create a simple program that displays a dialog box with the message Hello, world so that you can see the basics of script programming and how a script executes.

## Creating Your First Script in VBScript

To create the simple dialog box shown in Figure 1-2, you need only one line in VBScript:

    WScript.Echo "Hello, world"

Figure 1-2 A simple dialog box

But how do you create the script file? For this simple script, all you need is Notepad. Simply follow these steps:

1. Launch Notepad.exe and enter the statements shown in Figure 1-3. The WScript.Echo statement is the most important part of the code because it creates the dialog box.

Figure 1-3 Your first VBScript program

2. Save the contents of the editor window to a text file on your hard disk. You can use any filename (such as Hello), but the extension must be .vbs.

> NOTE

> I recommend that you use the .vbs extension for VBScript files. This file type is registered automatically for WSH. If your script files use other filename extensions, neither version of WSH can recognize the script language. Double-clicking a script file with a wrong extension (.vb, for example) will open the Open With dialog box because no application is registered for this file type.

After you store the script, there should be a file named Hello.vbs on your hard disk containing the source code in Listing 1-1.

Listing 1-1 Hello.vbs

    '************************************************
    ' File:    Hello.vbs (WSH sample in VBScript)
    ' Author:  (c) G. Born
    '
    ' Showing a simple dialog box
    '************************************************

    WScript.Echo "Hello, world"

    '*** End

You might wonder why I used eight lines even though I said that you needed just one command to invoke the dialog box. You can create a simple script file with just one line, but I encourage you to add comments with some additional information, such as your name (as the author of the file) and the purpose of the file. These comments can be helpful to other people and also to you. (Or do you always remember the purpose and contents of a script file after a few weeks? I don't!) The script engine ignores the comments.

Now let's go back to the code. Because we're using VBScript as the programming language, all statements must follow VBScript syntax. In VBScript, comments are marked with a leading single quote, as shown here:

    ' This is a comment.

The VBScript language engine used in WSH ignores any part of a line that follows a single quote. This means that you can comment an entire line or only the tail end of a line. For example, the following statement shows a dialog box with the text Hello, world. The comment at the end of the line is ignored.

    WScript.Echo "Hello, world"  ' Show a message.

> TIP

> The sample file Hello.vbs, along with all the other sample files used in this chapter, is in the folder \WSHDevGuide\Chapter01 on the book's companion CD. You'll also find the template files VBScript.vbs and JScript.js in that folder. You can use these files as templates to create a new script file. Simply load the template into your editor (by right-clicking on the file's icon and choosing Edit from the shortcut menu), add the new commands, and save the contents to a new file.

## Creating the Same Script in JScript

If you prefer JScript for your script programs, you can use the same steps we just discussed. However, you must enter all statements in JScript syntax. Listing 1-2 shows what the program from Listing 1-1 looks like in JScript.

Listing 1-2 Hello.js

    //************************************************
    // File:    Hello.js (WSH sample in JScript)
    // Author:  (c) G. Born
    //
    // Showing a simple dialog box
    //************************************************

    WScript.Echo("Hello, world");

    //*** End

In JScript, single-line comments are marked with two leading slashes (//) and the beginning and end of multiline comments are marked as follows: /* … */. Listing 1-2 contains a comment header and a trailer. I also used the Echo method from the WScript object to show the message box. (You'll find out about objects and methods in Chapter 3.)

The statement that creates a simple dialog box containing the text Hello, world and the OK button looks different in JScript:

    WScript.Echo("Hello, world");

Do you see the difference? In JScript, it's a good programming practice to terminate all statements (with a few exceptions) with semicolons, and the Echo method requires parentheses around the string "Hello, world".

## Executing WSH Scripts

If you have WSH scripts stored in .vbs or .js files, you can execute them in Windows by double-clicking on the script file's icon or by means of the Run dialog box, or you can execute them from the Command Prompt window.

### Executing a script in Windows

You can execute a script in Windows by simply double-clicking on the script file's icon. Windows executes the script using the WScript.exe host by default (because the file types are registered for WSH during WSH installation).

> NOTE

> Two files are used to implement WSH. WScript.exe is a Windows-based host for scripts, designed to interact with the user by means of dialog boxes. CScript.exe is a Windows console application. (It runs in a Command Prompt window and sends output to STDOUT like native MS-DOS and Windows NT commands do.) CScript.exe is intended primarily for noninteractive tasks. In Windows 98, WScript.exe is in the \Windows folder and CScript.exe is in the \Windows\Command folder. In Windows 2000, both hosts are in the \WINNT\System32 folder.

Let's give this a try. Find the file Hello.vbs in the folder \WSHDevGuide\Chapter01, and then double-click on Hello.vbs to start the sample. The result of the script is the dialog box shown back in Figure 1-2. If you double-click Hello.js, the resulting dialog box is identical to the one shown in Figure 1-2. You can close the dialog box from either sample by clicking the OK button.

You can also use the Run dialog box to execute a script in WScript.exe or CScript.exe. (This method comes in handy if you need to submit arguments to a script.) Simply follow these steps:

1. Choose Run from the Start menu.

2. Type the executable command (such as WScript.exe C:\Test\Hello.vbs) in the Open text box.

3. Click OK to close the dialog box and execute the script.

### Executing a script using the Command Prompt window

You can also use the Command Prompt window to execute a script. Both CScript.exe and WScript.exe support this approach.

To execute a script, you must enter the following command in the Command Prompt window:

    CScript.exe path\script name [Host options] [Script arguments]
    WScript.exe path\script name [Host options] [Script arguments]

The script name part is the placeholder for the script name, including the drive and the path to the script file. You can append additional options for the host and/or arguments for the script on the command line.

The host options, which enable or disable WSH functions, are always preceded by two forward slashes. Table 1-1 describes all the host options.

Table 1-1 CScript.exe and WScript.exe Host Options

Option | Supported by WSH 1 | Supported by WSH 2 | Description
--- | --- | --- | ---
//I | X | X | Enables interactive mode—allows display of user prompts and script errors. (This is the default; //B is the opposite.)
//B | X | X | Enables batch mode—suppresses the command-line display of user prompts and script errors. If a script uses the Echo method, all user prompts are disabled. In WSH 2, this option is also available for WScript.exe to disable echo mode.
//T:nn | X | X | Sets a time-out value (the maximum time in seconds that a script can run).
//logo | X | X | Displays a banner (the text shown in the Command Prompt window after execution of a script; see the upper lines in Figure 1-4). This is the default option; //nologo is the opposite.
//nologo | X | X | Prevents the display of an execution banner.
//H:CScript //H:WScript | X | X | Registers CScript.exe or WScript.exe as the default application for running scripts (//H:CScript or //H:WScript, respectively). WScript.exe is set to be the default scripting host after installation.
//S | X | X | Saves the current command-line options for this user.
//? | X | X | Displays a help page with the host options.
//D |  | X | Enables Active Debugging for .js and .vbs script files. (See Chapter 2.)
//E:engine |  | X | Sets the script engine for script execution.
//Job:xxx |  | X | Executes the job with the ID number xxx in a .wsf file.
//X |  | X | Executes the script in the debugger.

Figure 1-4 shows a Command Prompt window with sample command lines calling the script Hello.vbs with several options.

Figure 1-4 Command lines to call CScript.exe and WScript.exe

You can see a list of all the host options by invoking the host using the command CScript.exe //?. The dialog box in Figure 1-5 shows the WScript.exe options. (Choose Run from the Start menu, type WScript.exe //?, and click OK to close the dialog box.)

Figure 1-5 WScript.exe host options

### Setting the script properties

As I mentioned earlier, you can set several host options for executing a script within WScript.exe or CScript.exe. In a Command Prompt window, you can type the options on the command line. If you prefer to execute a script in Windows, you can use the Run dialog box to set host options for a script.

Users generally prefer to start scripts with a double-click (on the script file itself or on a shortcut file). In such cases, you can define additional properties in Windows by right-clicking on the script file, choosing Properties from the shortcut menu, and selecting the options you want on the Script property page (shown in Figure 1-6).

Figure 1-6 The Script property page

You can select the Stop Script After Specified Number Of Seconds check box and use the associated Seconds control to set a time-out value. If a script is still executing when the time-out is reached, Windows terminates the script. The Display Logo When Script Executed In Command Console check box forces CScript.exe to display the "Microsoft (R) Windows Script Host…" message in the Command Prompt window.

When you close the property page by clicking OK, Windows creates a new file with the name of the script file and a .wsh extension. Double-clicking on this file forces Windows to execute the script with the options set on the Script property page. Files with the extension .wsh are simple text files that are similar to .ini files. You can open a .wsh file with any text editor (such as Notepad). The contents of a .wsh file are as follows:

    [ScriptFile]
    Path=C:\WSHDevGuide\Chapter01\Hello.js
    [Options]
    Timeout=10
    DisplayLogo=1

The Path statement in the [ScriptFile] section identifies the script file to be executed. The keywords in the [Options] section determine the run-time properties. Timeout is set to the time the user specified on the Script property page. DisplayLogo=1 forces the display of the logo in the Command Prompt window. (See the //logo and //nologo entries in Table 1-1.)

> NOTE

> You can edit the Path statement in a .wsh file so that it uses a relative or Universal Naming Convention (UNC) path. Using a relative or UNC path makes your .wsh files and their targets more portable because it frees them from a dependence on an absolute path. For example, the sample file Args.wsh uses the statement Path=.\Args.vbs, which references the Args.vbs file in the current directory. You can move Args.wsh and Args.vbs to a new drive and Args.wsh will be able to find Args.vbs as long as both files are in the same directory.

## Submitting Arguments to a Script

The preceding samples don't require any arguments. In some cases, however, the user will submit one or more arguments, such as the name of a file, to the script. The VBScript in Listing 1-3 displays all arguments submitted to the script.

Listing 1-3 Args.vbs

    '************************************************
    ' File:     Args.vbs (WSH sample in VBScript)
    ' Author:  (c) G. Born
    '
    ' Showing all arguments submitted to the script
    ' in a dialog box
    '************************************************

    text = "Arguments" & vbCrLf & vbCrLf

    Set objArgs = WScript.Arguments       ' Create object.
    For i = 0 to objArgs.Count - 1        ' Loop through all arguments.
        text = text & objArgs(i) & vbCrLf ' Get argument.
    Next

    WScript.Echo text ' Show arguments using Echo.

    '*** End

The script in Listing 1-3 obtains the Arguments collection of the WScript object and shows all arguments contained in this collection in a dialog box, as shown in Figure 1-7.

Figure 1-7 Displaying submitted arguments

Let's assume that you have an existing script file and want to submit some arguments to this script. A double-click on the script file isn't sufficient because it simply executes the script. To submit arguments to a script, choose Run from the Start menu to display the Run dialog box (shown in Figure 1-8). You enter the host name (CScript.exe or WScript.exe), the drive, the pathname, and the filename of the script file in the Open text box. The arguments are appended to the command line; they must be separated with blanks.

Figure 1-8 Submitting arguments to a script using the Run dialog box

If you feel uncomfortable submitting arguments using the Run dialog box, you can create a shortcut to your script file and set the arguments as properties of the shortcut (as long as the arguments won't change). Simply follow these steps:

1. Right-click on the script's file icon and choose Create Shortcut from the shortcut menu.

2. Right-click on the shortcut file and choose Properties from the shortcut menu.

3. Specify the command and the required arguments in the Target text box on the Shortcut property page (as shown in Figure 1-9).

Figure 1-9 Shortcut properties for a script file

When you close the property sheet using the OK button, Windows saves the arguments. These arguments are submitted automatically to the script when the user double-clicks on the shortcut file.

### Passing arguments in the Command Prompt window

Does your script request arguments (such as a filename)? Do you use the Command Prompt window to execute your script (in CScript.exe or WScript.exe)? Besides specifying host options, which are preceded by two forward slashes, you can submit certain arguments as additional script options to the script. You simply place the script arguments at the end of the command line, separated by spaces.

You can thus call our Args.vbs sample in the Command Prompt window as follows:

    CScript.exe C:\WSHDevGuide\Chapter01\Args.vbs //S "Hello, world" 1 2 3
    WScript.exe C:\WSHDevGuide\Chapter01\Args.vbs //S "Hello, world" 1 2 3

Figure 1-10 shows some commands executed in a Command Prompt window using CScript.exe.

Figure 1-10 Executing a script and passing arguments in the Command Prompt window

> NOTE

> Because the individual arguments are optional, you must specify at least the name of the script file on the command line. You don't have to mark an argument with a forward slash, which is suggested in the WSH documentation. Also, you can mix the // options with the arguments to be passed to the script, as shown in the second command line in Figure 1-10.

In Figure 1-10, I used the JScript sample shown in Listing 1-4. This script uses the Echo method to show the submitted arguments. If you use CScript.exe as a host, the Echo method sends all output to the Command Prompt window (which is standard behavior for a Windows console program).

> TIP

> You can use this method with I/O redirection to send your script output to a file. The command CScript.exe D:\Test.vbs "Hello" 1 > D:\Test.tmp creates the file D:\Test.tmp and directs all script output to this file.

Listing 1-4 Args.js

    //************************************************
    // File:    Args.js (WSH sample in JScript)
    // Author:  (c) G. Born
    //
    // Displaying the script arguments in a dialog box
    //************************************************

    var objArgs;
    var text = "Arguments \n\n";

    var objArgs = WScript.Arguments;         // Create object.

    for (var i = 0; i < objArgs.length; i++) // Loop for all arguments.
        text = text + objArgs(i) + '\n';     // Get argument.

    WScript.Echo(text);  // Show arguments using Echo method.

    //*** End

## The New .wsf File Format

Although you can use .vbs and .js script files in WSH 2, Microsoft has defined a new file format with the extension .wsf (for "Windows script file"). A .wsf file is a text document, as .js and .vbs files are, but it contains Extensible Markup Language (XML) code. A minimal .wsf file has the following structure:

    <job id="T1">
        <script language="VBScript">
            WScript.Echo "Hello, world"
        </script>
    </job>

The tags describe XML elements, and the <script> … </script> element contains the ordinary script code.

> NOTE

> Because .wsf files are XML documents, you can use any editor that supports XML to edit them. If you don't have such an editor, you can use any other text editor (such as Notepad).

### Some XML extensions to .wsf files

The preceding sample code contains only the minimal XML elements required to create an executable .wsf file. For compatibility reasons with XML document specifications, I recommend using an extended structure within your .wsf files, as shown here:

    <?xml version="1.0" encoding="ISO-8859-1"?>

    <job id="T1">
        <script language="VBScript">
        <![CDATA[
            text = "world"
            WScript.Echo "Hello, " & text
        ]]>
        </script>
    </job>

The content of the <script> element is encapsulated in the instruction

    <![CDATA[ … ]]>

which tells an XML document reader that the content (here the script code) should not be analyzed for XML features. The encoding="ISO-8859-1" attribute allows your scripts to contain special characters of Western European alphabets, such as the German umlauts (for example, Ä and ö) and the French accents (for example, é and à).

> NOTE

> The .wsf samples shown in the help files don't use the <?xml...?> element. But I recommend that you use the instructions in this section so that your .wsf files are compatible with XML tools and future versions of WSH.

## Including External Files

If you have .js and .vbs files from previous WSH projects, you can use the .wsf file structure to include the files in a new WSH script. You can make the reference to the external .vbs or .js file within the <script> start tag using the src attribute. The following example includes the file Hello.js in the new WSH script Test.wsf:

    <?xml version="1.0" encoding="ISO-8859-1"?>

    <job id="T1">
        <script language="JScript" src="Hello.js"/>

        <script language="VBScript">
        <![CDATA[
            WScript.Echo "Hello, world number 2"
        ]]>
        </script>
    </job>

Executing the script file causes WSH to load and process the file Hello.js first. After control is passed back to the .wsf file, the second <script> element, which contains the WScript.Echo statement, is executed. You can also use the src attribute to define a reference to a script file containing only a function. Then you can call this function from within a script contained in the .wsf file.

> NOTE

> As you can see in the preceding sample, .wsf files enable you to combine scripts from different languages.

## Using Type Libraries

The <reference> element in a .wsf file enables you to use constants defined in a type library in scripts. The following <reference> element retrieves a reference from the type library of the FileSystemObject object:

    <reference guid='{420B2830-E718-11CF-893D-00A0C9054228}'/>

After defining such a reference, a script can use named constants exported from the type library. The following .wsf file sample shows the constants for drive types defined in the FileSystemObject object:

    <?xml version="1.0" encoding="ISO-8859-1"?>

    <job id="TypeLibExample">
        <reference guid='{420B2830-E718-11CF-893D-00A0C9054228}'/>

        <script language="VBScript">
        <![CDATA[
            WScript.Echo "CDRom = " & CDRom & vbCrLf & _
                         "Fixed = " & Fixed & vbCrLf & _
                         "RamDisk = " & RamDisk & vbCrLf & _
                         "Remote = " & Remote & vbCrLf & _
                         "Unknown = " & Unknown & vbCrLf & _
                         "Removable = " & Removable
        ]]>
        </script>
    </job>

I'll come back to the issue of using type libraries in Chapter 12, when we start dealing with drives, files, and folders. You can find a more in-depth discussion of the <reference> element, including techniques for finding the GUID value of type libraries, in Advanced Development with Microsoft Windows Script Host 2.0 (Microsoft Press, forthcoming).

## Debugging Features

You can use simple statements such as stop and debugger in your .vbs and .js script files (in WSH 1) to invoke the debugger (one that's already installed) automatically. To debug scripts in a WSH 2 environment, you must invoke your script using either the //D or the //X switch on the command line.

To debug a .wsf file by double-clicking it, use the <?job debug="true"?> processing instruction within your <job> elements. This instruction forces WSH to launch the script debugger if a stop or debugger instruction is found within a script. A <?job debug="false"?> statement within the <job> element disables the script debugger. The following code (sample file Test1.wsf) sets the <?job … ?> processing instruction in a .wsf file:

    <?xml version="1.0" encoding="ISO-8859-1"?>

    <job id="T1">
        <?job debug="true"?>

        <script language="VBScript">
            stop
            WScript.Echo "Hello"
        </script>

        <script language="JScript">
            debugger
            WScript.Echo("Hello1");
        </script>
    </job>