Home > Articles > Operating Systems, Server > Microsoft Servers

This chapter is from the book

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. Windows Mail 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).

Listing 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.

Listing 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.

Listing 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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020