[Previous] [Table of Contents] [Next]

Using the WScript Object

The WScript object is the WSH application object. It is exposed automatically when a script runs—you don't have to create a reference to it. The object exposes several methods and properties. In previous chapters, we used its Echo and Quit methods. In this chapter, we'll access the object's properties.

Retrieving WSH and Script Properties

In Chapter 6, I mentioned that certain attributes of WSH and the currently running script are available as read-only properties of the WScript object. If you execute a script in the Command Prompt window in Microsoft Windows using CScript.exe, the host program echoes the current version number on the command line. This version number is important because several different WSH versions are available. Properties such as the path to the host program and the host's name can also be useful. Table 7-1 describes some of the properties exposed by the WScript object.

Table 7-1 Properties of the WScript Object

Property Description
Application Returns the IDispatch interface of the WScript object
Arguments Returns a collection object containing the script arguments
FullName Contains the full path to the host executable (CScript.exe or WScript.exe)
Name The friendly name of WScript (This is the default property.)
Path The name of the directory in which the host (WScript.exe or CScript.exe) resides
ScriptFullName The full path to the script that is currently running in WSH
ScriptName The filename of the script that is currently running in WSH
Version A string containing the WSH version (not the language engine version)

NOTE
For further details about the WScript properties, see the Windows Script Host Reference, which you can find on this book's companion CD (in the \Docs\WSH folder) or at http://msdn.microsoft.com/scripting.

Now let's write a script that retrieves the host and script properties and displays the results in a dialog box. (See Figure 7-1.)

Figure 7-1 WScript host and script properties

It's easy to retrieve the properties of the WScript object. The WScript object is automatically exposed to the script from WSH during execution. The following statement reads the Application property of the WScript object and assigns this value to the variable Name:

Name = WScript.Application

If the script is executed in WSH, the variable contains the text Windows Scripting Host (for WSH 1) or Windows Script Host (for WSH 2). You can use this property to check whether the script is executed in a WSH environment (rather than in Microsoft Internet Explorer, for example, or as an external script of an Active Server Pages [ASP] file).

NOTE
The WSH properties can be helpful when you need the name of a script or the path of a script file. For additional information about WScript properties, see the Windows Script Host Reference.

Retrieving properties in VBScript

Listing 7-1 retrieves WScript properties by using VBScript. All you need is the object name WScript followed by a dot and then the property name. You use the following statement to retrieve the host name and assign it to a variable:

text = WScript.Name

This sample uses the Message variable to collect all properties in one string. The constant vbCrLf wraps the output onto several lines. The sample also uses the ScriptName property to show the script name in the dialog box title bar. (Like the other samples in this chapter, Properties.vbs is in the \WSHDevGuide\Chapter07 folder on the book's companion CD.)

Listing 7-1 Properties.vbs

'**************************************************
' File:    Properties.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born  
'
' Showing the properties of the WScript object
' in a dialog box
'**************************************************
Option Explicit

Dim Message
Dim Title

' Show the properties of the WScript object.
' We start with the host properties.
Message = "WScript host properties" & vbCrLf & vbCrLf
Message = Message & "Application: " & WScript.Application & vbCrLf
Message = Message & "Name: " & WScript.Name & vbCrLf
Message = Message & "Version: " & WScript.Version & vbCrLf
Message = Message & "FullName: " & WScript.FullName & vbCrLf
Message = Message & "Path: " & WScript.Path & vbCrLf 

' Get interactive status.
If (WScript.Interactive) Then
    Message = Message & "Interactive: True" & vbCrLf 
Else
    Message = Message & "Interactive: False" & vbCrLf 
End If

' Get script properties.
Message = Message & vbCrLf 
Message = Message & "WScript script properties" & vbCrLf & vbCrLf
Message = Message & "ScriptFullName: " & WScript.ScriptFullName & vbCrLf
Message = Message & "ScriptName: " & WScript.ScriptName & vbCrLf

' Initialize title.
Title = "WSH sample " & WScript.ScriptName & " - by G. Born"

MsgBox Message, vbInformation + vbOKOnly, Title

'*** End

Retrieving properties in JScript

In JScript, you can also retrieve the WScript properties by using the WScript object followed by a dot and then the property name, as shown in Listing 7-2. The information is collected in the Message variable. New lines in the output text are generated with the " \n " escape sequence.

Listing 7-2 Properties.js

//*************************************************
// File:     Properties.js (WSH sample in JScript)   
// Author:   (c) G. Born
// 
// Showing the properties of the WScript object
// in a dialog box
//*************************************************

var Message, Title, tmp;
var vbInformation = 64;    // A couple of constants
var vbOKOnly = 0;

// Collect the properties of the WScript object.
// Read the host properties.
Message = "WScript host properties\n\n";
Message = Message + "Application: " + WScript.Application + "\n";
Message = Message + "Name: " + WScript.Name + "\n";
Message = Message + "Version: " + WScript.Version + "\n";
Message = Message + "FullName: " + WScript.FullName + "\n";
Message = Message + "Path: " + WScript.Path + "\n"; 

// Get interactive status.
if (WScript.Interactive) 
    Message = Message + "Interactive: true" + "\n" 
else
    Message = Message + "Interactive: false" + "\n";

// Get the script properties.
Message = Message + "\n"; 
Message = Message + "WScript script properties\n\n";
Message = Message + "ScriptFullName: " + WScript.ScriptFullName + "\n";
Message = Message + "ScriptName: " + WScript.ScriptName + "\n";

// Initialize title.
Title = "WSH sample  " + WScript.ScriptName + " - by G. Born";

var objAdr = WScript.CreateObject("WScript.Shell");

tmp = objAdr.Popup(Message, vbInformation + vbOKOnly, Title);

//*** End

Retrieving Language Engine Properties

Besides the host and script properties, you might need the properties of the language engine. For example, you might want to request the version number from the interpreter. Both VBScript and JScript provide functions for checking the version of a language engine:

Retrieving language engine properties in VBScript

Listing 7-3 uses VBScript to query the language engine properties and display the results in a dialog box (shown in Figure 7-2).

Listing 7-3 Engine.vbs

'************************************************
' File:    Engine.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born
'
' Displaying the version of the language engine
'************************************************
Option Explicit

Dim txt

' Get the version of the language engine.
txt = "Language Engine: " & ScriptEngine() & vbCrLf
txt = txt & "Version: " & ScriptEngineMajorVersion() 
txt = txt & "." + CStr(ScriptEngineMinorVersion()) & vbCrLf
txt = txt & "Build: " + CStr(ScriptEngineBuildVersion())

WScript.Echo txt

'*** End

Figure 7-2 WScript language engine properties

Retrieving language engine properties in JScript

Listing 7-4 uses JScript to retrieve the properties of the language engine.

Listing 7-4 Engine.js

//************************************************
// File:    Engine.js (WSH sample in JScript) 
// Author:  (c) G. Born
//
// Displaying the version of the language engine
//************************************************

var txt = "Language Engine: " + ScriptEngine() + "\n" +
            "Version: " + ScriptEngineMajorVersion() +
            "." + ScriptEngineMinorVersion() + "\n" +
            "Build: " + ScriptEngineBuildVersion();

WScript.Echo(txt);

//*** End

Accessing Script Arguments

In Chapter 1, I explained some techniques for submitting arguments such as filenames or switches to a script. (See the section "Submitting Arguments to a Script.") You access these arguments within the script. Chapter 1 showed a script for displaying submitted arguments but didn't go into the details. Let's look at the details now.

You can use the WshArguments object in WSH to handle script arguments. Table 7-2 describes the properties associated with the WshArguments object.

Table 7-2 Properties of the WshArguments Object

Property Description
Count Returns the number of command line arguments
Item Default property that defines the nth argument on the command line, which is used to call the script
Length Returns the number of arguments and is used for JScript compatibility

How do you access these properties? Unfortunately, the WshArguments object is not exposed directly. You must use the Arguments property of the WScript object to access the script arguments. We'll look at the steps for VBScript.

The following statement assigns the Arguments property of the WScript object to the object variable objArgs:

Set objArgs = WScript.Arguments

The Set keyword is required because the property is a collection object, so objArgs must be an object variable. You can use objArgs to access the objects and their properties in this collection. You can access the first object of the collection by using the following statement:

Arg1 = objArgs(0)

In this case, the variable Arg1 receives the content of the default property of the object objArgs(0)—the first item of the collection. By the way, until now we've always used an object name and a property name, separated by a dot, to read a property value (as in WScript.Name). The preceding statement doesn't follow this scheme because the argument strings are in the Item property of the WshArguments object, and the Item property is the default property. Therefore, the statement above is equivalent to this statement:

Arg1 = objArgs.Item(0)

Both statements return the script argument stored in the Item property as a string into the variable Arg1.

But how do you get the number of submitted arguments in a collection? If the script is executed without an argument, the collection in the Arguments property is empty. Any attempt to access the object variable objArgs(0) causes a run-time error. According to Table 7-2, the WshArguments object obtained from the Arguments property also exposes the Count property, which you can use to check the number of items in the collection, which corresponds to the number of script arguments. Therefore, you can use the following code to access the first script argument:

If objArgs.Count >= 1 Then ' Is there at least one argument?
    Arg1 = objArgs.Item(0)
End If

If you want to access more than two arguments, this approach can become laborious. To access all script arguments, you should use a loop instead. The following VBScript code gets all arguments into a text variable:

For i = 0 To objArgs.Count - 1        ' Loop through all arguments.
    text = text & objArgs(i) & vbCrLf ' Get argument.
Next

You can retrieve the number of items in the collection by using objArgs.Count. Then you can use a simple For loop to process all the items. You can access an item using objArgs(i) because objArgs.Item(i) is the default property.

Accessing arguments in VBScript: Solution 1

Listing 7-5 uses the approach just described. If arguments are submitted to the script, the arguments are shown in a dialog box that lists each argument on a separate line (as in Figure 7-3). This script retrieves the number of items in the WshArguments collection and then uses a simple For loop to access each entry in the collection.

Figure 7-3 Displaying script arguments

Listing 7-5 Args.vbs

'************************************************
' File:    Args.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born  
'
' Showing script arguments in a dialog box
'************************************************
Option Explicit


Dim text, objArgs, i

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.

'*** End

You can submit arguments to the script in a shortcut file, the Run dialog box, or the Command Prompt window (as explained in Chapter 1). In WSH 2, you can also drag one or more files to the script file's icon. The dragged objects are submitted as arguments to the script.

NOTE
The shortcut file Args_vbs.lnk defines a command line for calling the script with predefined arguments. After copying Args.vbs and Args_vbs.lnk to a local folder, you must set the proper paths in the shortcut file.

Accessing arguments in VBScript: Solution 2

In VBScript, you can use a For Each…In loop to enumerate all elements in a collection (or an array); within the loop, you can evaluate each individual element:

For Each i In WScript.Arguments ' Loop through all arguments.
    text = text & i & vbCrLf    ' Get argument.
Next

The For Each i In WScript.Arguments statement processes each element in the collection. The loop index i contains the current element. Therefore, you can use the default value of the object i to read the script argument. The following code assigns the argument to the variable Arg1:

Arg1 = i

Listing 7-6 demonstrates the use of a For Each…In loop to access arguments in VBScript.

Listing 7-6 Args1.vbs

'************************************************
' File:    Args1.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born  
'
' Showing script arguments in a dialog box
'************************************************
Option Explicit

Dim text, objArgs, i

text = "Arguments" & vbCrLf & vbCrLf

Set objArgs = WScript.Arguments  ' Create object.
For Each i In objArgs            ' Loop through all arguments.
    text = text & i & vbCrLf     ' Get argument.
Next 

WScript.Echo text ' Show arguments.

'*** End

NOTE
The shortcut file Args1_vbs.lnk calls the script with predefined arguments.

Accessing arguments in JScript

In JScript, you can also access arguments by using the WScript.Arguments property, but the code used is slightly different. You don't need the Set keyword to access the Arguments property. JScript automatically creates the data subtype for the requested value. You can thus use the following statement to get the WshArguments collection:

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

This statement creates a variable and assigns the object reference. You can then access the items by using the following code:

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

This code assigns the content of the Item property (the default property of the WshArguments object) of the current element to the variable text. Note that in JScript you must use the Length property (instead of Count) to determine the number of items in the collection. This property is provided for compatibility purposes because the Count property causes a run-time error in JScript.

Listing 7-7 shows the entire script. If you execute this script with arguments, the arguments are shown in a dialog box similar to that in Figure 7-3.

Listing 7-7 Args.js

//************************************************
// File:    Args.js (WSH sample in JScript) 
// Author:  (c) G. Born  
//
// Showing 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 through all arguments.
    text = text + objArgs(i) + '\n';   // Get argument.
 
WScript.Echo(text);  // Show arguments.

//*** End

NOTE
The shortcut file Args_js.lnk calls the script with predefined arguments.