Flylib.com

Books Software

 
 
 

Microsoft VBScript Professional Projects - page 50


Summary

In this chapter, you learned about the DOM and DHTML object models. You also learned how to develop scripts that interact with the objects provided by these object models in order to enhance your control over your HTML pages. In addition, you learned about browser events and how to set up event handlers in order to develop procedures that allow you to create interactive HTML pages.



Chapter 9: VBScript and the WSH

In this chapter, you will learn about the objects, properties, and methods provided by the WSH. Later, you will learn how to use these objects to access and manipulate a host of Windows resources. This chapter will also demonstrate how to create scripts that can receive and process arguments passed at run time. Finally, you'll learn how to create a new kind of script file using XML ( Extensive Markup Language ) that will allow you to combine two or more separate scripts, written in different scripting languages, together into one new Windows Script File.

The WSH Object Model

At the heart of the WSH is its core object model. The objects that make up this model provide direct access to the Windows resources that they represent. In total, the WSH core object model is made up of 14 objects. These objects and their relationship to one another are depicted in Figure 9.1.

click to expand
Figure 9.1: The WSH core object model is made up of 14 individual objects

The WScript object resides at the top or root of the object model. The WScript object is implicitly instantiated by the WSH at the start of script execution, meaning that scripts can automatically access any of its properties or methods. All of the other objects in the WSH core object model must first be instantiated in order to use their properties and methods.

Public Objects

The WScript object is automatically exposed at the start of script execution. The WScript object is also referred to as a public object. The WSH core object model has three other public objects, which are the WshController , WshShell , and WshNetwork objects. In order to instantiate any of these three objects, you must use the WScript object's CreateObject() method. The remaining WSH core objects are instantiated by using one of the properties or methods of these four public objects.

Note 

The WScript object's CreateObject() method provides the means of instantiating other objects in the WSH core object model.

Table 9.1 provides a list of the other 10 objects that make up the WSH core object model and a list of object properties or methods that are required to instantiate them.

Table 9.1: Working with Lower-Level WSH Objects

Object

Method of Instantiation

WshArguments

WScript.Arguments

WshNamed

WScript.Arguments.Named

WshUnnamed

WScript.Arguments.Unnamed

WshRemote

WshController.CreateScript()

WshRemoteError

WshRemote.Error

WshShortcut

WshShell.CreateShortcut()

WshUrlShortcut

WshShell.CreateShortcut()

WshEnvironment

WshShell.Environment

WshSpecialFolders

WshShell.SpecialFolders

WshScriptExec

WshShell. Exec ()

WSH Object Properties and Methods

Each object in the WSH core object model has its own unique set of properties and methods. Table 9.2 provides a brief description of the WSH core objects. In addition, it provides a list of properties and methods associated with each object.

Table 9.2: WSH Core Objects

Object

Description

WScript

This is the WSH root object. It provides access to a number of useful properties and methods. It also provides access to the rest of the objects in the WSH core object model.

Properties: Arguments , FullName , Interactive , Name , Path , ScriptFullName , ScriptName , StdErr , StdIn , StdOut , and Version

Methods: ConnectObject() , CreateObject() , DisconnectObject() , Echo() , GetObject() , Quit() , and Sleep()

WshArguments

This object allows you to access command-line arguments passed to the script at execution time.

Properties: Count , Item , and Length ; Named and Unnamed

Methods: Count() and ShowUsage()

WshNamed

This object provides access to a set of named command-line arguments.

Properties: Item and Length

Methods: Count() and Exists()

WshUnnamed

This object provides access to a set of unnamed command-line arguments.

Properties: Item and Length

Methods: Count()

WshController

This object provides the ability to create a remote script process.

Properties: This object does not support any properties.

Methods: CreateScript

WshRemote

This object provides the ability to administrate remote computer systems using scripts over a network.

Properties: Status and Error

Methods: Execute() and Terminate()

WshRemoteError

This object provides access to information on errors produced by remote scripts.

Properties: Description , Line , Character , SourceText , Source , and Number

Methods: This object does not support any methods.

WshNetwork

This object provides access to a number of different network resources such as network printers and drives .

Properties: ComputerName , UserDomain , and UserName

Methods: AddWindowsPrinterConnection() , AddPrinterConnection() , EnumNetworkDrives() , EnumPrinterConnection() , MapNetworkDrive() , RemoveNetworkDrive() , RemovePrinterConnection() , and SetDefaultPrinter()

WshShell

This object provides access to the Windows registry, event log, environmental variables , shortcuts, and applications.

Properties: CurrentDirectory , Environment , and SpecialFolders

Methods: AppActivate() , CreateShortcut() , ExpandEnvironmentStrings() , LogEvent() , Popup() , RegDelete() , RegRead() , RegWrite() , Run() , SendKeys() , and Exec()

WshShortcut

This object provides scripts with methods and properties for creating and manipulating Windows shortcuts.

Properties: Arguments , Description , FullName , Hotkey , I conLocation , TargetPath , WindowStyle , and WorkingDirectory

Method: Save()

WshUrlShortcut

This object provides scripts with methods and properties for creating and manipulating URL shortcuts.

Properties: FullName and TargetPath

Methods: Save()

WshEnvironment

This object provides access to Windows environmental variables.

Properties: Item and Length

Methods: Remove() and Count()

WshSpecialFolders

This object provides access to special Windows folders that allow scripts to configure the Start menu, desktop, Quick Launch toolbar, and other special Windows folders.

Properties: Item

Methods: Count()

WshScriptExec

This object provides access to error information from scripts run using the Exec method.

Properties: Status , StdOut , StdIn , and StdErr

Methods: Terminate()

{% if main.adsdop %}{% include 'adsenceinline.tpl' %}{% endif %}

There are too many WSH objects to cover them all in a single chapter. Therefore, this chapter will be limited to providing you with a WSH object reference, while offering a few examples of how to work with some of the WSH objects. The remaining chapters of this book will give you the opportunity to work with many of the properties and methods belonging to the objects shown in Table 9.2.

Core Object Properties

Object properties store information about the resources that they represent. By referencing object properties, VBScript can collect information about the environment in which they execute. Further, by modifying object properties, VBScripts can make direct changes to this environment and the Windows resources that reside within it.

The WSH core objects provide access to dozens of different properties. Table 9.3 lists each of these properties.

Table 9.3: WSH Object Properties

Property

Description

Arguments

Sets a pointer reference to the WshArguments collection

AtEndOfLine

Returns either True or False depending on whether the end-of-line maker has been reached in the stream

AtEndOfStream

Returns either True or False depending on whether the end of the input stream has been reached

Character

Identifies the specific character in a line of code where an error occurs

Column

Returns the current column position in the input stream

ComputerName

Retrieves a computer's name

CurrentDirectory

Sets or retrieves a script's current working directory

Description

Retrieves the description for a specified shortcut

Environment

Sets a pointer reference to the WshEnvironment

Error

Provides the ability to expose a WshRemoteError object

ExitCode

Returns the exit code from a script started using Exec()

FullName

Retrieves a shortcut or executable program's path

HotKey

Retrieves the hotkey associated with the specified shortcut

IconLocation

Retrieves an icon's location

Interactive

Provides the ability to programmatically set script mode

Item

Retrieves the specified item from a collection or provides access to items stored in the WshNamed object

Length

Retrieves a count of enumerated items

Line

Returns the line number for the current line in the input stream or identifies the line number within a script where an error occurred

Name

Returns a string representing the name of the WScript object

Number

Provides access to an error number

Path

Returns the location of the folder where the CScript or WScript execution hosts reside

ProcessID

Retrieves the PID ( process ID ) for a process started using the WshScriptExec object

ScriptFullName

Returns an executing script's path

ScriptName

Returns the name of the executing script

Source

Retrieves the identity of the object that caused a script error

SourceText

Retrieves the source code that created the error

SpecialFolders

Provides access to the Windows Start menu and desktop folders

Status

Provides status information about a remotely executing script or a script started with Exec()

StdErr

Enables a script to write to the error output stream or provides access to read-only error output from an Exec object

StdIn

Enables read access to the input stream or provides access to the write-only input scream for the Exec object

StdOut

Enables write access to the output stream or provides access to the write-only output stream of the Exec object

TargetPath

Retrieves a shortcut's path to its associated object

UserDomain

Retrieves the domain name

UserName

Retrieves the currently logged on user 's name

Version

Retrieves the WSH version number

WindowStyle

Retrieves a shortcut's window style

WorkingDirectory

Returns the working directory associated with the specified shortcut

Note 

In some cases, the same property may be shared by more than one object. Use Table 9.2 to determine which properties are associated with which objects.

Using WSH Object Properties

As an example of how to work with WSH object properties, review the following VBScript. In this script, the properties belonging to the WshNetwork object are referenced in order to collect network information.

'************************************************************************* 'Script Name: Script 9.1.vbs 'Author: Jerry Ford 'Created: 02/12/03 'Description: This script

demonstrates

how to use properties belonging to 'the WshNetwork object in order to obtain network information '************************************************************************* 'Initialization Section Option Explicit Dim WshNtwk, strDisplayText 'Instantiate the WshNetwork object Set WshNtwk = WScript.CreateObject("WScript.Network") 'Main Processing Section 'Call the procedure that collects and displays network information DisplayNetInfo() 'Terminate script execution WScript.Quit() 'Procedure Section 'This subroutine Display network information Sub DisplayNetInfo() strDisplayText = "This computer is " & WshNtwk.ComputerName & ". " & _ "It is connected to the following domain:" & vbCrLf & vbCrLf & _ WshNtwk.UserDomain & vbCrLf & vbCrLf & vbCrLf MsgBox strDisplayText, , "Network Information" End Sub

This script begins by defining two variables, WshNtwk and strDisplayText . WshNtwk is then used to instantiate the WshNetwork object, as shown below.

Dim WshNtwk, strDisplayText Set WshNtwk = WScript.CreateObject("WScript.Network")

As you can see, both the Set statement and the WScript object's Create-Object() method are required to set up an instance of the WshNetwork object. Once instantiated, you can reference any of the object's properties and methods. Next, the script executes a procedure called DisplayNetInfo() . This subroutine contains two statements. The first statement creates a display string using the strDisplayText variable and the following WshNetwork properties:

  • ComputerName . Retrieves the network name assigned to the computer where the script executes

  • UserDomain . Retrieves the domain name of the Windows domain to which the computer belongs, or if the computer is a member of a workgroup-based network, retrieves the name of the workgroup to which the computer has been assigned

The second statement in the DisplayNetInfo() subroutine displays the display string as demonstrated in Figure 9.2. Finally, control returns to the Main Processing Section, where the WScript object's Quit() method is used to terminate the script's execution.

click to expand
Figure 9.2: Displaying network information collected from properties belonging to the WshNetwork object

Core Object Methods

WSH object methods provide the ability to interact with and manipulate the resources that they represent. These resources include desktop shortcuts, the Windows file systems, printers, and the Windows registry. Table 9.4 provides a list of WSH core object methods.

Table 9.4: WSH Object Methods

Method

Description

AddPrinterConnection()

Creates printer mappings

AddWindowsPrinterConnection()

Creates a new printer connection

AppActivate()

Activates the targeted application Window

Close()

Terminates or ends an open data stream

ConnectObject()

Establishes a connection to an object

Count

Retrieves the number of switches found in the WshNamed and WshUnnamed objects

CreateObject()

Creates a new instance of an object

CreateScript()

Instantiates a WshRemote object representing a script that is running remotely

CreateShortcut()

Creates a Windows shortcut

DisconnectObject()

Terminates a connection with an object

Echo()

Displays a text message

EnumNetworkDrives()

Enables access to network drives

EnumPrinterConnections()

Enables access to network printers

Exec()

Executes an application in a child command shell and provides access to the environment variables

Execute()

Initiates the execution of a remote script object

Exists()

Determines a specified key exists within the WshNamed object

ExpandEnvironmentStrings()

Retrieves a string representing the contents of the Process environmental variable

GetObject()

Retrieves an Automation object

GetResource()

Retrieves a resource's value as specified by the <resource> tag

LogEvent()

Writes a message in the Windows event log

MapNetworkDrive()

Creates a network drive mapping

Popup()

Displays a text message in a pop-up dialog box

Quit()

Terminates or ends a script

Read()

Retrieves a string of characters from the input stream

ReadAll()

Retrieves the s string that is made up of the characters in the input stream

ReadLine()

Retrieves a string containing an entire line of data from the input stream

RegDelete()

Deletes a registry key or value

RegRead()

Retrieves a registry key or value

RegWrite()

Creates a registry key or value

Remove()

Deletes the specified environmental variable

RemoveNetworkDrive()

Deletes the connection to the specified network drive

RemovePrinterConnection()

Deletes the connection to the specified network printer

Run()

Starts a new process

Save()

Saves a shortcut

SendKeys()

Emulates keystrokes and sends typed data to a specified Window

SetDefaultPrinter()

Establishes a default Windows printer

ShowUsage()

Retrieves information regarding the way that a script is supposed to be executed

Skip()

Skips x number of characters when reading from the input stream

SkipLine()

Skips an entire line when reading from the input stream

Sleep()

Pauses script execution for x number of seconds

Terminate()

Stops a process started by Exec()

Write()

Places a string in the output stream

WriteBlankLines()

Places a blank in the output stream

WriteLine()

Places a string in the output stream

Using WSH Object Methods

As an example of how to work with WSH object methods, examine the following VBScript. In this VBScript, methods belonging to the WshShell object are used to set up a mapped drive connection to a network folder.

'************************************************************************* 'Script Name: Script 9.2.vbs 'Author: Jerry Ford 'Created: 02/12/03 'Description: This script demonstrates how to use methods belonging to 'the WshNetwork object in order to map a network drive '************************************************************************* 'Initialization Section Option Explicit Dim WshNtwk, strDriveLetter, strDrivePath strDriveLetter = "z:" strDrivePath = "\\FamilyPC\D" 'Instantiate the WshNetwork object Set WshNtwk = WScript.CreateObject("WScript.Network") 'Main Processing Section 'Call the procedure that maps network drives MapDrive strDriveLetter, strDrivePath 'Terminate script execution WScript.Quit() 'Procedure Section 'This subroutine creates a network drive mapping Sub MapDrive(strLetter, strPath) 'Create a mapping to the specified network drive WshNtwk.MapNetworkDrive strLetter, strPath End Sub

The script's Initialization Section contains statements that perform the following tasks :

  • Define variables to represent the WshNetwork object, a drive letter, and the address of a network folder

  • Assign a drive letter and the address of the network folder

  • Instantiate the WshNetwork object

Next, the Main Processing Section executes the MapDrive() procedure, passing the drive letter and the address of the network folder, as shown below.

MapDrive strDriveLetter, strDrivePath

The MapDrive() subroutine receives the arguments passed to it and assigns them to two new variables. It then uses the WshNetwork object's MapNetwork-Drive() method to establish the drive mapping. Finally, control returns to the Main Processing Section, where the WScript object's Quit() method is used to terminate the script's execution. Figure 9.3 shows how the mapped network drive appears in the My Computer dialog box.

click to expand
Figure 9.3: Mapping a network drive using the WshNetwork object's MapNetworkDrive() method