Programming the WScript Object
The WScript object represents the Windows Script Host applications (WScript.exe and CScript.exe). You use this object to get and set certain properties of the scripting host, as well as to access two other objects: WshArguments (the WScript object's Arguments property) and WshScriptEngine (accessed via the WScript object's GetScriptEngine method). WScript also contains the powerful CreateObject and GetObject methods, which enable you to work with Automation-enabled applications.
Displaying Text to the User
The WScript object method that you'll use most often is the Echo method, which displays text to the user. Here's the syntax:
WScript.Echo [Argument1, Argument2,...]
Here, Argument1 , Argument2 , and so on, are any number of text or numeric values that represent the information you want to display to the user. In the Windows-based host (WScript.exe), the information displays in a dialog box; in the command-line host (CScript.exe), the information displays at the command prompt (much like the command-line ECHO utility).
Shutting Down a Script
You use the WScript object's Quit method to shut down the script. You can also use Quit to have your script return an error code by using the following syntax:
WScript.Quit [intErrorCode]
intErrorCode |
An integer value that represents the error code you want to return |
You could then call the script from a batch file and use the ERRORLEVEL environment variable to deal with the return code in some way. (See Appendix C for more information on ERRORLEVEL.)
Scripting and Automation
Applications such as Internet Explorer and Word come with (or expose, in the jargon) a set of objects that define various aspects of the program. For example, Internet Explorer has an Application object that represents the program as a whole. Similarly, Word has a Document object that represents a Word document. By using the properties and methods that come with these objects, it's possible to programmatically query and manipulate the applications. With Internet Explorer, for example, you can use the Application object's Navigate method to send the browser to a specified web page. With Word, you can read a Document object's Saved property to see whether the document has unsaved changes.
This is powerful stuff, but how do you get at the objects that these applications expose? You do that by using a technology called Automation. Applications that support Automation implement object libraries that expose the application's native objects to Automation-aware programming languages. Such applications are Automation servers, and the applications that manipulate the server's objects are Automation controllers. The Windows Script Host is an Automation controller that enables you to write script code to control any server's objects.
This means that you can use an application's exposed objects more or less as you use the Windows Script Host objects. With just a minimum of preparation, your script code can refer to and work with the Internet Explorer Application object, or the Microsoft Word Document object, or any of the hundreds of other objects exposed by the applications on your system. (Note, however, that not all applications expose objects. Outlook Express and most of the built-in Windows Vista programs—such as WordPad and Paint—do not expose objects.)
Creating an Automation Object with the CreateObject Method
The WScript object's CreateObject method creates an Automation object (specifically, what programmers call an instance of the object). Here's the syntax:
WScript.CreateObject(strProgID)
strProgID |
A string that specifies the Automation server application and the type of object to create. This string is a programmatic identifier, which is a label that uniquely specifies an application and one of its objects. The programmatic identifier always takes the following form: |
AppName.ObjectType |
|
Here, AppName is the Automation name of the application and ObjectType is the object class type (as defined in the Registry's HKEY_CLASSES_ROOT key). For example, here's the programmatic ID for Word: |
|
Word.Application |
Note that you normally use CreateObject within a Set statement, and that the function serves to create a new instance of the specified Automation object. For example, you could use the following statement to create a new instance of Word's Application object:
Set objWord = CreateObject("Word.Application")
You need to do nothing else to use the Automation object. With your variable declared and an instance of the object created, you can use that object's properties and methods directly. Listing 12.1 shows a VBScript example (you must have Word installed for this to work).
Example 12.1. A VBScript Example That Creates and Manipulates a Word Application Object
' Create the Word Application object ' Set objWord = WScript.CreateObject("Word.Application") ' ' Create a new document ' objWord.Documents.Add ' ' Add some text ' objWord.ActiveDocument.Paragraphs(1).Range.InsertBefore "Automation test." ' ' Save the document ' objWord.ActiveDocument.Save ' ' We're done, so quit Word ' objWord.Quit
This script creates and saves a new Word document by working with Word's Application object via Automation. The script begins by using the CreateObject method to create a new Word Application object, and the object is stored in the objWord variable. From there, you can wield the objWord variable just as though it were the Word Application object.
For example, the objWord.Documents.Add statement uses the Documents collection's Add method to create a new Word document, and the InsertBefore method adds some text to the document. The Save method then displays the Save As dialog box so that you can save the new file. With the Word-related chores complete, the Application object's Quit method runs to shut down Word. For comparison, Listing 12.2 shows a JavaScript procedure that performs the same tasks.
Example 12.2. A JavaScript Example That Creates and Manipulates a Word Application Object
// Create the Word Application object // var objWord = WScript.CreateObject("Word.Application"); // // Create a new document // objWord.Documents.Add(); // // Add some text // objWord.ActiveDocument.Paragraphs(1).Range.InsertBefore("Automation test."); // // Save the document // objWord.ActiveDocument.Save(); // // We're done, so quit Word // objWord.Quit();
Working with an Existing Object Using the GetObject Method
If you know that the object you want to work with already exists or is already open, the CreateObject method isn't the best choice. In the example in the previous section, if Word is already running, the code will start a second copy of Word, which is a waste of resources. For these situations, it's better to work directly with the existing object. To do that, use the GetObject method:
WScript.GetObject(strPathname, [strProgID])
strPathname |
The pathname (drive, folder, and filename) of the file you want to work with (or the file that contains the object you want to work with). If you omit this argument, you have to specify the strProgID argument. |
strProgID |
The programmatic identifier that specifies the Automation server application and the type of object to work with (that is, the AppName.ObjectType class syntax). |
Listing 12.3 shows a VBScript procedure that puts the GetObject method to work.
Example 12.3. A VBScript Example That Uses the GetObject Method to Work with an Existing Instance of a Word Document Object
' Get the Word Document object ' Set objDoc = WScript.GetObject("C:\GetObject.doc", "Word.Document") ' ' Get the word count ' WScript.Echo objDoc.Name & " has " & objDoc.Words.Count & " words." ' ' We're done, so quit Word ' objDoc.Application.Quit
The GetObject method assigns the Word Document object named GetObject.doc to the objDoc variable. After you've set up this reference, you can use the object's properties and methods directly. For example, the Echo method uses objDoc.Name to return the filename and objDoc.Words.Count to determine the number of words in the document.
Note that although you're working with a Document object, you still have access to Word's Application object. That's because most objects have an Application property that refers to the Application object. In the script in Listing 12.3, for example, the following statement uses the Application property to quit Word:
objDoc.Application.Quit
Exposing VBScript and JavaScript Objects
One of the most powerful uses for scripted Automation is accessing the object models exposed by the VBScript and JavaScript engines. These models expose a number of objects, including the local file system. This enables you to create scripts that work with files, folders, and disk drives, read and write text files, and more. You use the following syntax to refer to these objects:
Scripting.ObjectType
Scripting is the Automation name of the scripting engine, and ObjectType is the class type of the object.
Programming the FileSystemObject
FileSystemObject is the top-level file system object. For all your file system scripts, you begin by creating a new instance of FileSystemObject:
In VBScript:
Set fs = WScript.CreateObject("Scripting.FileSystemObject")
In JavaScript:
var fs = WScript.CreateObject("Scripting.FileSystemObject");
Here's a summary of the file system objects you can access via Automation and the top-level FileSystemObject:
-
Drive
— This object enables you to access the properties of a specified disk drive or UNC network path. To reference a Drive object, use either the Drives collection (discussed next) or the FileSystemObject object's GetDrive method. For example, the following VBScript statement references drive C:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objDrive = objFS.GetDrive("C:")
-
Drives
— This object is the collection of all available drives. To reference this collection, use the FileSystemObject object's Drives property:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objDrives = objFS.Drives
-
Folder
— This object enables you to access the properties of a specified folder. To reference a Folder object, use either the Folders collection (discussed next) or the FileSystemObject object's GetFolder method:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder("C:\My Documents")
-
Folders
— This object is the collection of subfolders within a specified folder. To reference this collection, use the Folder object's Subfolders property:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder("C:\Windows")
Set objSubfolders = objFolder.Subfolders
-
File
— This object enables you to access the properties of a specified file. To reference a File object, use either the Files collection (discussed next) or the FileSystemObject object's GetFile method:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.GetFile("c:\autoexec.bat")
-
Files
— This object is the collection of files within a specified folder. To reference this collection, use the Folder object's Files property:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder("C:\Windows")
Set objFiles = objFolder.Files
-
TextStream
— This object enables you to use sequential access to work with a text file. To open a text file, use the FileSystemObject object's OpenTextFile method:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objTS= objFS.OpenTextFile("C:\Boot.ini")
- Alternatively, you can create a new text file by using the FileSystemObject object's CreateTextFile method:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objTS= objFS.CreateTextFile("C:\Boot.ini")
- Either way, you end up with a TextStream object, which has various methods for reading data from the file and writing data to the file. For example, the following script reads and displays the text from C:\Boot.ini:
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile("C:\Boot.ini")
strContents = objTS.ReadAll
WScript.Echo strContents
objTS.Close