The WSH Object Model

When using VBScript to write WSH scripts, you use VBScript to access the WSH object model. The Windows Script Host object model, a small and fairly shallow object model with a number of createable objects, is shown in Figure 7-1.

Figure 7-1. The Windows Scripting Host object model

figs/vbs2.0701.gif

WSH is not intended to be a self-contained, all-encompassing object model. It focuses on three major areas:

  • Providing resources necessary to support script execution. For instance, the WScript object reports on the interpreter and version of WSH in use, while the WshShell object allows shortcuts and Internet shortcuts to be created.
  • Enhancing the ease with which a system can connect to and disconnect from network resources. This functionality is supported by the WshNetwork object.
  • Supporting functionality that is not readily available in other object models. For example, the WshShell object allows access to environment variables and to the location of Windows system folders.

Through the CreateObject and GetObject methods of the WScript object, WSH allows you to take advantage of the functionality supported by other objects that support COM automation. This topic is discussed in Section 7.6 later in this chapter. The remainder of this section provides concise documentation on the objects that form the WSH object model, along with their properties and methods.

7.4.1 The WScript Object

The WScript object, the top-level object in the WSH object model, provides information about the script host (that is, about WScript.exe or CScript.exe) and the script file it is executing as well as provides access to other objects. This object is instantiated automatically by the host whenever a WSH script is launched; you don't have to retrieve a reference to it. (In fact, calls to either CreateObject or GetObject will fail to return a reference to the WScript object.) The properties of the WScript object are listed in Table 7-2, while its methods appear in Table 7-3.

Table 7-2. Properties of the WScript object

Property

Description

Application

Returns a reference to the WScript object itself, which can be passed as an argument to external routines.

Arguments

Returns a WshArguments object consisting of several collections of strings containing the command-line arguments (both named and unnamed) passed to the script when it was invoked; see the entry for the WshArguments object later in this chapter for details.

Fullname

The full path and filename of the script host file (which is usually either WScript.exe or CScript.exe).

Name

The friendly name of the script host file. For example, the friendly name of both WScript.exe and CScript.exe is "Windows Script Host." It is the default property of the WScript object.

Path

The full path (without the filename) to the script host.

ScriptFullName

The full path and filename of the script being executed.

ScriptName

Returns a string containing the filename of the script file being executed.

StdErr

Returns a reference to a write-only TextStream object that provides access to the script's standard error stream when CScript.exe is the WSH host. Typically, the error output stream is sent to the console.

The TextStream object is part of the File System object model available from the Microsoft Scripting Runtime Library. Because it is write-only, the TextStream object returned by the StdErr property supports only the following methods:

Close

Write

WriteBlankLines

StdIn

Returns a reference to a read-only TextStream object that provides access to the script's standard input stream when CScript.exe is the WSH host. Typically, standard input to a program comes from the keyboard, though it can also be provided by a source defined by the command-line redirection character. For example, in the following statement, the standard input is the contents of the file Greeting.txt:

CScript.exe ShowGreeting.vbs < Greeting.txt

Any attempt to read input that is unavailable causes the respective read method to block. The read-only TextStream object returned by the StdIn property supports the following properties and methods:

AtEndOfLine

AtEndOfStream

Column

Line

Close

Read

ReadAll

ReadLine

Skip

StdOut

Returns a reference to a write-only TextStream object that provides access to the script's standard output stream when CScript.exe is the WSH interpreter. Typically, standard output from a program goes to the screen; it can also go to a device defined by the command-line redirection character. For example, the output is redirected to the first parallel printer:

CScript.exe ShowGreeting.vbs > Greeting.txt

The TextStream object returned by StdOut supports these:

Close

Write

WriteBlankLines

Version

The version of the script host.

Table 7-3. Methods of the WScript object

Method

Description

CreateObject

Instantiates a new instance of a class. Its syntax is WScript.CreaterObject(strProgID[,strPrefix]) where strProgID is the programmatic identifier of the object to be created as defined in the registry and strPrefix is an optional string that instructs WSH to trap the object's events (if it has any) and to fire public event handlers whose names begin with strPrefix concatenated with the event name. The method returns a reference to the new object. For example:

Set oRate = _
 WScript.CreateObject("Component1.Rate", "oRate_")

Public Sub oRate_RateChanged( )
 WScript.Echo "RateChanged event fired!"
End Sub

The chief difference between the VBScript CreateObject function and the WScript CreateObject method is that the latter allows you to trap the events raised by an object.

ConnectObject

Connects an object's events to functions beginning with a designated prefix. Its syntax is WScript.ConnectObject strobject, strPrefix where strobject is a reference to the object whose events are to be trapped, and strPrefix is the prefix of the event handler for the events. Note that the documentation incorrectly indicates that strObject is the name of the object whose events are to be trapped. The event handler whose name is a concatenation of strPrefix and the event name is automatically invoked; for example:

WScript.ConnectObject oRate, "oRate_"

Public Sub oRate_RateChanged( )
 WScript.Echo "RateChanged event fired!"
End Sub

Calling the ConnectObject method is equivalent to supplying a strPrefix parameter when retrieving an object reference using either the CreateObject or GetObject method of the WScript object. In addition, ConnectObject allows you to handle events raised by objects not createable by the CreateObject or GetObject methods.

Some objects that source events do not allow runtime discovery of those events. Such objects cannot be connected with either the CreateObject or the ConnectObject methods of the WScript object.

DisconnectObject

This method simply "disconnects" an event sync; that is, it "disconnects" the object "connected" by the ConnectObject method. Its syntax is WScript.DisconnectObject obj where obj is a reference to the object whose events are no longer to be handled. If the events raised by obj are not currently being trapped, calling the method has no effect.

Echo

Sends output to a dialog box (if the host is WScript.exe) or the console (for CScript.exe). Its syntax is WScript.Echo [arg1, [arg2...]] where arg1 and arg2 are the expressions to be output. If multiple arguments are present, a space is used to separate them. If none are present, the method outputs a blank line.

GetObject

Returns a reference to an existing instance of a class. Its syntax is WScript.GetObject(strPathname [,strProgID], [strPrefix]) where strPathname is the path and name of the file containing the object to retrieve, strProgID is the programmatic identifier of the object to be created as defined in the registry, and strPrefix is an optional string that instructs WSH to trap the object's events (if it has any) and to fire public event handlers whose names begin with strPrefix concatenated with the event name. The method returns a reference to the object.

Quit

Terminates script execution and raises an error. Its syntax is WScript.Quit [intErrorCode] where intErrorCode is the number of the error to raise.

ShowUsage

Displays help information explaining how to use a script.

Sleep

Suspends script execution for a specified number of milliseconds. Its syntax is WScript.Sleep(intTime) where intTime is the number of milliseconds to wait. Events continue to fire and event handlers continue to run while sleeping.

7.4.2 The WshArguments Object

The WshArguments object is a collection object returned by the Arguments property of the WScript object; it cannot be created by calls to the WScript object's CreateObject or GetObject methods. The following statement returns a WshArguments collection object:

Dim oArgs
Set oArgs = WScript.Arguments

It consists of one string for each command-line argument passed to the script when it was invoked. You can iterate the arguments as follows:

Dim arg
For Each arg in oArgs
 ' Do something with arg, the individual argument
Next

Or you can retrieve an individual argument using code like the following, which retrieves the first argument in the collection:

Dim arg
arg = WScript.Arguments.Item(0)

WSH supports both named and unnamed arguments. Named arguments are passed to a script by using the syntax:

scriptname /ArgName:ArgValue

ArgName, the argument name, is preceded by a single slash, while the argument name and ArgValue, the value of the named argument, are separated from one another by a colon. Unnamed arguments are entered on the command line as values only, with no special syntax; for example:

scriptname ArgValue

Both named and unnamed arguments are included in the collection. The arguments can be filtered into named and unnamed arguments by using the WshArguments object's Named and Unnamed properties.

The properties of the WshArguments object are shown in Table 7-4.

Table 7-4. Properties of the WshArguments object

Property

Description

Count

Indicates the number of arguments in the collection.

Item

Returns a string argument given its ordinal position (or index) in the collection. The first argument is at position 0. Item is the default member of the WshArguments collection.

length

Like the Count method, returns the number of arguments in the collection.

Named

Returns a WshNamed object containing the named arguments passed to the script when it was invoked. For details, see the entry for the WshNamed object later in this chapter.

Unnamed

Returns a WshUnnamed object containing the unnamed arguments passed to the script when it was invoked. For details, see the entry for the WshUnnamed object later in this chapter.

7.4.3 The WshController Object

The WshController object, which is new toWSH 5.6, allows for the creation of a remote script process. WshController is a createable object that must be instantiated with a code fragment like the following:

Dim cnt
Set cnt = WScript.CreateObject("WSHController")

The WshController object has a single method,CreateScript, as shown in Table 7-5. It is this method that accesses the script to be run remotely and returns a WshRemote object that provides some control over the resulting script process. For an example of using remote scripting, see Section 7.4.7 later in this chapter.

Table 7-5. Method of the WshController object

Name

Description

CreateScript

Returns a WshRemote object, which represents a remote script process. Its syntax is object.CreateScript(CommandLine,[MachineName]) where object is a reference to a WshConnection object, CommandLine provides the name of the script to execute (along with an optional path and any command-line switches and parameters), and MachineName is an optional parameter containing the UNC name of the system on which the script is to execute. If MachineName is omitted, the script executes on the system on which the WshController object is instantiated. If CommandLine identifies a different system than MachineName, the script is loaded from the system identified by CommandLine but run on the system identified by MachineName.

7.4.4 The WshEnvironment Object

The WshEnvironment object is a collection object returned by the Environment property of the WshShell object; it cannot be created by calls to the WScript object's CreateObject or GetObject methods.

WshEnvironment is a collection of strings containing a set of environment variables. Windows systems maintain two such sets of environment variables, either of which can be returned by the Environment property of the WshShell object:

  • A system table, which is retrieved by supplying the string System as an argument to the Environment property of the WshShell object. The system table contains the environment variables available to all processes running on the system.
  • A process table, which is retrieved by supplying the string Process as an argument to the Environment property of the WshShell object. The process table contains the environment variables defined for the individual process. It also includes the environment variables in the system table.

The members of the WshEnvironment object are shown in Table 7-6.

Since the WshEnvironment object is a child of the WshShell object, it requires that a WshShell object be instantiated. This requires that you access the WshEnvironment collection through a code fragment like the following:

Dim wsh, env
Set wsh = WScript.CreateObject("WScript.Shell")
Set env = wsh.Environment

You can then iterate the collection as follows:

Dim str
For Each str in env
 sMsg = sMsg & str & vbCrLf
Next

WScript.Echo sMsg

Table 7-6. Members of the WshEnvironment object

Name

Type

Description

Count

Property

Indicates the number of environment variables in the collection.

Item

Property

Returns an environment variable's name/value pair (separated by an equals sign) if passed a string containing its name (or key). Item is the default member of the WshEnvironment collection. Hence, the code:

WScript.Echo(WshShell.Environment.Item("Path"))

is functionally identical to the code:

WScript.Echo(WshShell.Environment("Path"))

length

Property

Indicates the number of environment variables in the collection.

Remove

Method

Removes an environment variable from the collection. Its syntax is WshEnvironment.Remove strName where strName is a String representing the name of the environment variable. Attempting to delete a variable based on its ordinal position in the collection has no effect.

7.4.5 The WshNamed Object

The WshNamed object, which is new to WSH 5.6, is a collection object that contains named command-line arguments. (A named argument is entered on the command line with the syntax /name:value.) WshNamed is not a createable object, and is returned by theNamed property of the WshArguments object.

The following statement returns a WshNamed collection object:

Dim namedArgs
Set namedArgs = WScript.Arguments.Named

It consists of one string for each named command-line argument passed to the script when it was invoked. You can iterate the arguments as follows:

Dim arg
For Each arg in namedArgs
 ' Do something with arg, the individual named argument
Next

Or you can retrieve an individual argument using code like the following, which retrieves the first named argument in the collection:

Dim arg
arg = WScript.Arguments.Named(0)

The members of the WshNamed object are listed in Table 7-7.

Table 7-7. Members of the WshNamed object

Name

Type

Description

Count

Method

Returns an integer indicating the number of named arguments in the collection. Its syntax is object.Count( ).

Exists

Method

Returns a Boolean indicating whether a particular named argument exists in the collection. Its syntax is object.Exists(strArgName) where strArgName is a String containing the argument name.

Item

Property

Returns a String containing the value of a particular named command line argument. Its syntax is: object.Item(strArgName) where strArgName is a String containing the argument name. If strArgName is not found in the collection, the property returns an empty string.

Since Item is the default member of the WshNamed object, it need not be called explicitly. Hence, the following two lines of code function identically:

strVal = oNamed.Item("name")
strVal = oNamed("name")

length

Property

Returns an integer indicating the number of named arguments in the collection.

7.4.6 The WshNetwork Object

The WshNetwork object representsnetwork resources that are available to a client computer. You can create a WshNetwork object with a code fragment like the following:

Dim oNet
Set oNet = WScript.CreateObject("WScript.Network")

The WshNetwork object supports the three properties shown in Table 7-8 and the eight methods shown in Table 7-9.

Table 7-8. Properties of the WshNetwork object

Property

Description

ComputerName

Returns a String containing the name of the local computer.

UserDomain

Returns a String containing the name of the user domain.

UserName

Returns a String containing the username.

Table 7-9. Methods of the WshNetwork object

Method

Description

AddPrinterConnection

Maps a remote printer to a local resource name. Its syntax is WshNetwork.AddPrinterConnection strLocalName, strRemoteName [,bUpdateProfile] [, strUser][, strPassword] where strLocalName is the local resource name, strRemoteName is the name of the remote resource, bUpdateProfile is an optional Boolean that indicates whether the user profile is to be updated to contain this mapping, strUser is the optional name of the user for whom the printer is being mapped, and strPassword is the password of the user for whom the printer is mapped.

AddWindowsPrinterConnection

Adds a printer connection. Its syntax for Windows NT/2000/XP is WshNetwork AddWindowsPrinterConnection(strPrinterPath) where strPrinterPath is the path to the printer. Under Windows 95/98/ME, its syntax is:

WshNetwork.AddWindowsPrinterConnection(strPrinterPath, strDriverName[, strPort])

where strPrinterPath is the path to the printer, strDriverName is the name of the printer driver to use, and strPort is the optional name of the port to which to attach the printer. The default value of strPort is LPT1.

This method differs from the AddPrinterConnection method by not requiring that the printer be assigned a local port.

EnumNetworkDrives

Returns a zero-based collection of strings containing the current network drive mappings. All members having even index values are local names (drive letters), and all having odd index values are the remote names of the immediately preceding local drive. The collection returned by the method supports the following properties:

Count

The number of items in the collection

Item

Returns an individual item from the collection

length

The number of items in the collection

EnumPrinterConnections

Returns a zero-based collection of strings containing the current network printer mappings. All members having even index values are the ports, and all members having odd index values are the network mappings of the preceding port. The collection returned by the method has the following members:

Count

The number of items in the collection

Item

Returns an individual item from the collection

length

The number of items in the collection

MapNetworkDrive

Maps a network share to a local resource. Its syntax is WshNetwork.MapNetworkDrive strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword] where strLocalName is the local resource, strRemoteName is the network resource, bUpdateProfile is a Boolean value that indicates whether the user's profile should be updated to include the mapping, strUser is the optional name of the user for whom the printer is being mapped, and strPassword is the optional password of the user for whom the printer is being mapped.

RemoveNetworkDrive

Removes a current resource connection. Its syntax is WshNetwork.RemoveNetworkDrive strName, [bForce], [bUpdateProfile] where strName must be either a local name (if the remote drive is mapped to a local name) or a remote name, bForce is a Boolean value that indicates whether the connection should be removed even if the resource is in use, and bUpdateProfile is a Boolean that indicates whether the mapping should be removed from the user profile.

RemovePrinterConnection

Removes the connection to a network printer. Its syntax is WshNetwork.RemovePrinterConnection strName, [bForce], [bUpdateProfile] where strName must be a local name (if the printer is mapped to a local name) or a remote name, bForce is a Boolean value that indicates whether the printer should be removed even if it is in use, and bUpdateProfile is a Boolean that indicates whether the connection should be removed from the user profile.

SetDefaultPrinter

Sets the default printer to a remote printer. Its syntax is WshNetwork.SetDefaultPrinter strPrinterName where strPrinterName is the name of the remote printer. The names of available remote printers can be retrieved with the EnumPrinterConnection method.

7.4.7 The WshRemote Object

The WshRemote object, which is new to WSH 5.6, allows for control over a remote script by the launching script. It is returned by the CreateScript method of the WshController object. The WshRemote object supports the members shown in Table 7-10. Note that, unlike most of the objects in the Windows Script Host object model, the WshRemote object supports three events: Start, End, and Error.

Configuring Remote Scripting

Before you can launch a script remotely, the system on which it runs has to be configured to support remote scripting. This requires that Windows Script Host 5.6 be installed on the remote machine, that the user launching the remote script be a member of the remote machine's Local Administrators group, and that remote scripting be enabled in the registry. The HKEY_LOCAL_MACHINESoftwareMicrosoftWindows Script HostSettings key has a value entry named Remote. If its value is 1, remote scripting is enabled; if 0, disabled. The following script enables the key:

Dim oShell, regKey, regValue
Set oShell = CreateObject("WScript.Shell")
regKey = "HKLMSoftwareMicrosoftWindows Script HostSettingsRemote"
regValue = oShell.RegRead(regKey)
If regValue = "0" Then
 regValue = "1"
 oShell.RegWrite regKey, regValue, "REG_SZ"
End If

Table 7-10. Members of the WshRemote object

Name

Type

Description

End

Event

Fired when a remote script completes execution either because the WshRemote object's Terminate method is called or because the script has itself terminated.

Error

Property

Returns a WshRemoteError object that, if retrieved from the WshRemote object's Error event handler, provides information about the error that caused a remote script to terminate.

Error

Event

Fired when an error occurs in the remote script. No parameters are passed to the event handler.

Execute

Method

Starts the execution of a remote script. Its syntax is: object.Execute( ).

Start

Event

Fired when the WshRemote object's Execute method is called to begin execution of a remote script.

Status

Property

Returns the status of the remote script. Possible values are NoTask (0), Running (1), and Finished (2).

Terminate

Method

Prematurely terminates the execution of a remote script.

The following example illustrates the use of remote scripting and the WshRemote object. A controller script launches remote scripts on a number of systems in order to assemble a report listing those systems with drives whose free space is under 200 MB. The following .wsf file launches the remote scripts:








 
 This script uses remote scripting to examine the disk drives 
 of designated systems and reports those with less than 
 200MB free.
 



The script reads a text file, MachineList.txt, which contains a list of the systems whose drives are to be checked for available space, one system per line. For each machine, it calls the WshController object's CreateScript method, which returns a reference to a WshRemote object. The first parameter to the CreateScript method is the name of the script to be run along with an unnamed argument, the machine name. The argument is included because this makes it very easy for the remote script to identify the system on which it is running. The second parameter of the CreateScript method is once again the name of the system on which the remote script is to run.

The call to the CreateScript method returns a reference to a WshRemote object, which is then used in the call to the WScript object's ConnectObject method so that the script can receive event notifications. The script then executes the following remote script and enters a loop until the remote script has completed, at which point it disconnects the event handler and reads another line if one is present in MachineList.txt:

Option Explicit

Const ForAppending = 8
Const ForReading = 1
Const ForWriting = 2
Const Fixed = 2
Const fn = "c:ooksvbscript ianwshfreespace.txt"

Dim fs, drives, drive
Dim overWrite
Dim freeSpace
Dim msg

' Retrieve object references
Set fs = CreateObject("Scripting.FileSystemObject")
Set drives = fs.Drives

overWrite = True
 ' Enumerate drives
For Each drive In drives
 ' Examine only fixed drives
 If drive.IsReady And drive.DriveType = Fixed Then
 freeSpace = drive.FreeSpace
 ' Log if under 200MB free
 If freeSpace < 200000000 Then
 ' Form message string
 msg = msg & "System: " & WScript.Arguments.Unnamed(0) & " "
 msg = msg & "Drive " & drive.DriveLetter & ": " & _
 FormatNumber(drive.FreeSpace, 0, False, True, True) _
 & " free" 
 msg = msg & " Date: " & Date() & " " & Time( )
 WriteToFile msg
 overwrite = False
 End If
 End If
Next

Sub WriteToFile(strToWrite)

 Dim mode, create 
 Dim ts

 mode = ForAppending
 create = False
 
 Set ts = fs.OpenTextFile(fn, mode, create)
 ts.WriteLine strToWrite
 ts.Close
End Sub

When the remote script begins and ends, its Start and End events, respectively, are fired. This executes the remote_Start and remote_End event handlers in the controller script, which write information about the beginning and end of the remote script to the controller's event log. If an error occurs, information about it is also written to the controller's event log.

7.4.8 The WshRemoteError Object

The WshRemoteError object provides access to information about the error that caused a remote script to terminate execution. The object is new to WSH 5.6. The WshRemoteError object is not createable; instead, it is returned by the Error property of the WshRemote object. The property's value is typically retrieved in the Error event handler of the WshRemote object. To see the use of the WshRemoteError object in a script, see the example in Section 7.4.7 earlier in this chapter.

The properties of the WshRemoteError object are listed in Table 7-11.

Table 7-11. Properties of the WshRemoteError object

Property

Description

Character

Returns the character position in a line at which the error occurred, or a 0 if a line and character position could not be identified as containing the source of the error.

Description

Returns a String containing a brief description of the error, or an empty string if none is available.

Line

Returns the number of the line on which the error occurred, or a 0 if a line containing the source of the error could not be identified.

Number

Returns a Long containing the error number.

Source

Identifies the COM object in which the error occurred.

SourceText

Returns the line of script containing the error, or an empty string if no line could be identified.

7.4.9 The WshScriptExec Object

The WshScriptExec object represents a local script or application launched by calling the WshShell.Exec method. Its members provide status information and allow you to access the script or application's standard input, output, and error streams. The WshScriptExec object is new to WSH 5.6.

The members of the WshScriptExec object are listed in Table 7-12.

Table 7-12. Members of the WshScriptExec object

Name

Type

Description

Status

Property

Returns status information about a script or application run using the WshShell.Exec method. Possible values are WshRunning (0) and WshFinished (1).

StdErr

Property

Provides access to the WshScriptExec's standard error stream.

StdIn

Property

Provides access to the WshScriptExec's standard input stream.

StdOut

Property

Provides access to the WshScriptExec's standard output stream.

Terminate

Method

Sends a WM_CLOSE message to a process (a script or an application) launched by calling the WshShell.Exec method. How the message is handled depends on the application: it can ignore the message, or it can terminate.

7.4.10 The WshShell Object

The WshShell object provides access to a wide variety of shell services, such asregistry access, access toenvironment variables and to the location of system folders, and the ability to create shortcuts and to start processes. You can instantiate a WshShell object with a code fragment like the following:

Dim wsh
Set wsh = WScript.CreateObject("WScript.Shell")

The WShell object supports the 3 properties shown in Table 7-13 and the Table 7-11 methods listed in Table 7-14.

Table 7-13. Properties of the WshShell object

Property

Description

CurrentDirectory

A read-write property that determines the script's current directory.

Environment

Returns a WshEnvironment collection containing the system or process environment variables and their values. Its syntax is oShell.Environment([strType]) where strType is an optional string indicating which table of environment variables (System or Process) the property should return. For details, see the WshEnvironment object. If omitted, the property returns the system environment variables on Windows NT/2000/XP and the process environment variables on Windows 95/98/ME.

SpecialFolders

Returns a WshSpecialFolders collection containing the names of system folders and their locations; for details, see the WshSpecialFolders object.

Table 7-14. Methods of the WshShell object

Method

Description

AppActivate

Activates an application window. Its syntax is WshShell.AppActivate title where title is the caption of the application to be activated. If there is no exact match, WSH will attempt to match title with the application window whose caption begins with title. The documentation mentions that title can also be the task ID, which is returned by the Shell function; the Shell function, however, is present in VB but not in VBScript or WSH.

CreateShortcut

Returns a reference to a new or an existing WshShortcut object. Its syntax is WshShell CreateShortcut- (strPathname) where strPathname is the path and filename of an existing or a new Windows shortcut file (a file with an extension of *.lnk). (If strPathname has an extension of *.url, the method returns a reference to a WshUrlShortcut object instead.)

Once you retrieve the object reference, you can create or modify the physical shortcut file by calling the WshShortcut object's Save method.

Exec

Runs a script or application as a separate process and returns a WshScriptExec object that provides access to its standard input, standard output, and standard error. The method is new to WSH 5.6.

ExpandEnvironmentStrings

Expands an environment variable and returns its value. Its syntax is WshShell.ExpandEnvironmentStrings (strString) where strString is a string that includes the name of an environment variable delimited by a beginning and closing percentage sign (%).

LogEvent

Logs an event. Its syntax is WshShell.LogEvent(intType, strMessage [,strTarget]) where intType defines the type of event and is one of the values in Table 7-15, strMessage is the text of the event message, and, for Windows NT/2000/XP only, strTarget is the optional name of the system on which the event should be logged. If strTarget is omitted, the event is logged on the local system. Under Windows NT/2000/XP, events are logged in the Windows NT event log. Under Windows 95/98/ME, they're logged in the WSH.log file in the user's Windows directory; each entry contains the date and timestamp, the event type, and the text of the log message. The method returns True if successful and False otherwise.

Popup

Displays a popup message box. Its syntax is:

intButton = WshShell.Popup(strText, [natSecondsToWait], 
[strTitle], [natType])

where strText is the text of the message to appear in the pop up, natSecondsToWait is the optional number of seconds to wait before automatically closing the pop up, strTitle is the optional pop-up dialog's caption (it defaults to "Windows Script Host" if omitted), and natType defines the types of buttons and icons to use in the pop-up window and has the same values as the Win32 MessageBox function. This can consist of any one icon type combined with (i.e., logically Or'ed with) any one button set shown in Table 7-16. The method returns one of the integers shown in Table 7-17, which indicates which button is pressed to close the pop up.

RegDelete

Deletes a key or value from the registry. Its syntax is WshShell.RegDelete strName where strName is the path to the key or value to delete. If strName ends in a backslash, it denotes a key; otherwise, it denotes a value. The default (or unnamed) value of a key cannot be deleted; it must be replaced with an empty string ("") by using the RegRead method. The abbreviations for the top-level registry keys are shown in Table 7-18.

RegRead

Returns a registry value. Its syntax is WshShell.RegRead- (strName) where strName is the path to the value to read. If strName ends in a backslash, the method reads the key's default value; otherwise, it reads a named value. The abbreviations for the top-level keys are shown in Table 7-18; keys not listed must be accessed by their full name (e.g., HKEY_ CURRENT_CONFIG). The RegRead method can read the data types shown in Table 7-19; other data types are not supported. Note that the RegRead method does not expand environment strings in REG_EXPAND_SZ data; this requires a separate call to the WshShell object's ExpandEnvironmentStrings method.

RegWrite

Writes a registry value. Its syntax is WshShell.RegWrite strName, anyValue [,strType] where strName is that path to the value to write. If strName ends in a backslash, the method writes the key's default value; otherwise, it writes a named value. The abbreviations for the top-level registry keys are shown in Table 7-18; keys not listed must be accessed by their full names (e.g., HKEY_USERS).The RegWrite method can read the data types shown in Table 7-19; other data types are not supported.

Run

Creates a new process. Its syntax is WshShell.Run (strCommand, [intWindowStyle], [bWaitOnReturn]) where strCommand represents the command to execute, along with any command-line parameters. Any environment variable in it will be expanded automatically. intWindowStyle is an optional integer that defines the window style of the new process (for a list of valid window styles, see Table 7-20), and bWaitOnReturn is an optional Boolean synchronization flag that determines whether control returns to the script only after the process ends; by default, control returns to the script immediately after the Run method is called. The value returned by the function is 0 if bWaitOnReturn is False; otherwise, the method returns any error code returned by the application.

SendKeys

Sends keystrokes to the active window as if they were typed at the keyboard. Its syntax is SendKeys string where string is a string expression that specifies the keystrokes to send. Except for the special symbols shown in Table 7-21, each keyboard character is represented in string by itself.

The SendKeys method cannot be used to send keystrokes to a non-Windows application. Nor can SendKeys be used to send the Print Screen key to any window.

Table 7-15. Values of the intType parameter of the LogEvent method

Value

Description

0

Success

1

Error

2

Warning

4

Information

8

Audit_Success

16

Audit_Failure

Table 7-16. Values of the natType parameter of the Popup method

Type

Value

Description

Button

0

OK

Button

1

OK and Cancel

Button

2

Abort, Retry, Ignore

Button

3

Yes, No, Cancel

Button

4

Yes, No

Button

5

Retry, Cancel

Icon

16

Stop

Icon

32

Question

Icon

48

Exclamation

Icon

64

Information

Table 7-17. Return values of the Popup method

Value

Description

1

OK button

2

Cancel button

3

Abort button

4

Retry button

5

Ignore button

6

Yes button

7

No button

Table 7-18. Abbreviations for the top-level registry keys

Abbreviation

Key

HKCU

HKEY_CURRENT_USER

HKLM

HKEY_LOCAL_MACHINE

HKCR

HKEY_CLASSES_ROOT

Table 7-19. Data types supported by the WshShell registry methods

Data type

RegWrite string constant

RegRead/RegWrite variant type

string

"REG_SZ"

String

string with macros

"REG_EXPAND_SZ"

String

string array

not supported

String array

long integer

"REG_DWORD"

Long

binary data (byte array)

"REG_BINARY"

Variant array of bytes

Table 7-20. Values of the intWindowStyle parameter of the Run method

Value

Description

0

Hides the window and activates another window.

1

Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. This flag should be used when specifying an application for the first time.

2

Activates the window and displays it minimized.

3

Activates the window and displays it maximized.

4

Displays a window in its most recent size and position. The active window remains active.

5

Activates the window and displays it in its current size and position.

6

Minimizes the specified window and activates the next top-level window in the Z order.

7

Displays the window as a minimized window. The active window remains active.

8

Displays the window in its current state. The active window remains active.

9

Activates and displays the window. If it is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.

10

Sets the show state based on the state of the program that started the application.

Table 7-21. Special characters for use with the SendKeys method

Key

String

Key

String

Shift

+

Scroll Lock

{SCROLLLOCK}

Ctrl

^

Tab

{TAB}

Alt

%

Up Arrow

{UP}

Backspace

{BACKSPACE}, {BS}, or {BKSP}

F1

{F1}

Break

{BREAK}

F2

{F2}

Caps Lock

{CAPSLOCK}

F3

{F3}

Delete

{DELETE} or {DEL}

F4

{F4}

Down Arrow

{DOWN}

F5

{F5}

End

{END}

F6

{F6}

Enter

{ENTER} or ~

F7

{F7}

Esc

{ESC}

F8

{F8}

Help

{HELP}

F9

{F9}

Home

{HOME}

F10

{F10}

Insert

{INSERT} or {INS}

F11

{F11}

Left Arrow

{LEFT}

F12

{F12}

Num Lock

{NUMLOCK}

F13

{F13}

Page Down

{PGDN}

F14

{F14}

Page Up

{PGUP}

F15

{F15}

Print Screen

{PRTSC}

F16

{F16}

Right Arrow

{RIGHT}

   

7.4.11 The WshShortcut Object

The WshShortcut object represents a shortcutthat is, a link to a file or other resource on the local system or local network. A new or existing WshShortcut object is returned by the CreateShortcut method of the WshShell object, as in the following code fragment:

Set WshShell = WScript.CreateObject("WScript.Shell")
Set oSCut = WshShell.CreateShortcut("Startup Script.lnk")

A WshShortcut object exists in memory only and not in the filesystem until it is saved by calling the object's Save method.

When a new shortcut object is created, its FullName property is assigned the value specified by the strPathname parameter. The remaining properties assume their default values and must be changed programmatically before calling the WshShortcut object's Save method.

The WshShortcut object supports the eight properties shown in Table 7-22 and the single method shown in Table 7-23.

Table 7-22. Properties of the WshShortcut object

Property

Description

Arguments

Sets or returns a single String representing the arguments passed to the shortcut.

Description

Sets or returns a String representing a description of the shortcut. The Description property is not visible from the Windows user interface.

FullName

Returns a String containing the full path and filename of the shortcut file. Shortcut files have a file extension of *.lnk.

Hotkey

Sets or returns a String containing the keyboard shortcut that executes the shortcut file; hotkeys apply only to shortcuts located on the Windows desktop or on the Start menu. Multiple keys are joined by a "+" sign. For example, a Hotkey value of "Alt+Ctrl+A" indicates that the shortcut's hotkey is the Alt + Ctrl + A key combination.

According to the documentation, strings indicating alphabetic keys are case-sensitive ("A" is an uppercase A, but "a" is lowercase), although this does not appear to be the case. The strings that represent some common nonalphanumeric hotkeys are listed in Table 7-24.

IconLocation

Defines the location of the shortcut's icon. Typically, its value is the complete path and filename to the file containing the icon followed by a comma and the zero- based position of the icon within the file. If the default icon is used, the value of IconLocation is " ,0".

TargetPath

Sets or returns the path and filename to the shortcut's executable file. Note that the value of the TargetPath property can also include a data file that's associated with an executable file.

WindowStyle

Defines the window style of the application launched by the shortcut. Valid values are shown in Table 7-25.

WorkingDirectory

Defines the shortcut's working directory (i.e., the directory in which the shortcut will start).

Table 7-23. Method of the WshShortcut object

Method

Description

Save

Saves the Shortcut object to the filesystem at the location specified by the FullName property. Its syntax is WshShortcut.Save.

Table 7-24. Some common nonalphanumeric hotkey strings

Hotkey String

Description

Alt

Alt key

Back

Backspace key

Ctrl

Ctrl key

Escape

Esc key

Shift

Shift key

Space

Space key

Tab

Tab key

Table 7-25. Values of the WindowStyle property

Value

Description

1

Activates and displays a window.

3

Activates the window and displays it maximized.

7

Displays the window as a minimized window. The active window remains active.

7.4.12 The WshSpecialFolders Object

WshSpecialFolders is a collection object that stores strings that indicate the location of Windowssystem folders, like the Desktop folder of the Windows System folder. The collection is returned by the SpecialFolders property of the WshShell object, as the following code fragment shows:

Dim oShell, oSpFolders

Set oShell = WScript.CreateObject("WScript.Shell")
Set oSpFolders = oShell.SpecialFolders

Note that the location of a particular WshSpecialFolders object can be accessed by using its key, as discussed in the entry for the object's Item property in Table 7-26.

The WshSpecialFolders object supports the standard three properties of a WSH collection object, as shown in Table 7-26.

Table 7-26. Properties of the WshSpecialFolders object

Property

Description

Count

Indicates the number of items in the collection.

Item

Returns an individual item from the collection; each item is a string that indicates the location of a particular special folder. If the member doesn't exist, the Item property returns an empty variant. An item is retrieved from the collection either by its ordinal position in the collection or by its key; valid key values are: AllUsersDesktop, AllUsersStartMenu, AllUsersPrograms, AllUsersStartup, Desktop, Favorites, Fonts, MyDocuments, NetHood, PrintHood, Programs, Recent, SendTo, StartMenu, Startup, and Templates.

length

Indicates the number of items in the collection.

7.4.13 The WshUnnamed Object

The WshUnnamed object, which is new toWSH 5.6, is a collection object that contains unnamed command-line arguments. (An unnamed argument is entered on the command line by itself with no special syntax.) WshUnnamed is not a createable object, and is returned by the Unnamed property of the WshArguments object.

The following statement returns a WshUnnamed collection object:

Dim unnamedArgs
Set unnamedArgs = WScript.Arguments.Unnamed

It consists of one string for each unnamed argument passed to the script when it was invoked. You can iterate the arguments as follows:

Dim arg
For Each arg in unnamedArgs
 ' Do something with arg, the individual argument
Next

Or you can retrieve an individual argument using code like the following, which retrieves the first unnamed argument in the collection:

Dim arg
arg = WScript.Arguments.Unnamed(0)

The members of the WshUnnamed object are shown in Table 7-27.

Table 7-27. Members of the WshUnnamed object

Name

Type

Description

Count

Method

Returns an integer indicating the number of unnamed arguments in the collection. Its syntax is: object.Count( ).

Item

Property

Returns a String containing the value of a command-line argument at a particular ordinal position in the collection. Its syntax is: object.Item(intPos) where intPos is an Integer indicating the ordinal position of the argument. If intPos is outside of the range of the collection, an error occurs.

Since Item is the default member of the WshUnnamed object, it need not be explicitly referenced. Hence, the following two lines of code function identically:

strVal = oUnnamed.Item(2)
strVal = oUnnamed(2)

length

Property

Returns an integer indicating the number of named arguments in the collection.

7.4.14 The WshUrlShortcut Object

The WshUrlShortcut object represents anInternet shortcutan Internet link to an Internet resource. A new or an existing WshUrlShortcut object is returned by the CreateShortcut method of the WshShell object, as in the following code fragment:

Set WshShell = WScript.CreateObject("WScript.Shell")
Set oURL = WshShell.CreateShortcut("Favorite Website.url")

A WshUrlShortcut object exists in memory only and not in the filesystem until it is saved by calling the object's Save method.

When a new WshUrlShortcut object is created, its FullName property is assigned the value specified by the strPathname parameter.

Its remaining property, TargetPath, must be changed programmatically before calling the WshUrlShortcut object's Save method.

The WshUrlShortcut object supports the three members shown in Table 7-28.

Table 7-28. Members of the WshUrlShortcut object

Member type

Member name

Description

Property

FullName

Returns a String containing the full path and filename of the Internet shortcut file. Shortcut files have a file extension of *.url.

Property

TargetPath

Sets or returns a String containing the complete URL of the Internet resource to which the Internet shortcut is linked.

Method

Save

Saves the Internet shortcut object to the filesystem at the location specified by the FullName property. Its syntax is WshUrlShortcut.Save .

Part I: The Basics

Introduction

Program Structure

Data Types and Variables

Error Handling and Debugging

VBScript with Active Server Pages

Programming Outlook Forms

Windows Script Host 5.6

VBScript with Internet Explorer

Windows Script Components

Part II: Reference

Part III: Appendixes

Appendix A. Language Elements by Category

Appendix B. VBScript Constants

Appendix C. Operators

Appendix E. The Script Encoder



Vbscript in a Nutshell
VBScript in a Nutshell, 2nd Edition
ISBN: 0596004885
EAN: 2147483647
Year: 2003
Pages: 335

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net