Windows script host 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 .

Updated: April 2009

The Windows Script Host object model consists of 14 objects. The root object is the WScript object.

The illustration that follows represents the Windows Script Host Object Model hierarchy.

The Windows Script Host Object Model Hierarchy

The Windows Script Host object model provides a logical, systematic way to perform many administrative tasks. The set of COM interfaces it provides can be placed into two main categories:

  • Script Execution and Troubleshooting

    This set of interfaces allows scripts to perform basic manipulation of the Windows Script Host, output messages to the screen, and perform basic COM functions such as CreateObject and GetObject.

  • Helper Functions

    Helper functions are properties and methods for performing actions, such as mapping network drives, connecting to printers, retrieving and modifying environment variables, and manipulating registry keys. Administrators can also use the Windows Script Host helper functions to create simple logon scripts.

The following table is a list of the WSH objects and the typical tasks associated with them.

Object

What you can do with this object


WScript Object

  • Set and retrieve command line arguments

  • Determine the name of the script file

  • Determine the host file name (wscript.exe or cscript.exe)

  • Determine the host version information

  • Create, connect to, and disconnect from COM objects

  • Sink events

  • Stop a script’s execution programmatically

  • Output information to the default output device (for example, a dialog box or the command line)


WshArguments Object

Access the entire set of command-line arguments


WshNamed Object

Access the set of named command-line arguments


WshUnnamed Object

Access the set of unnamed command-line arguments


WshNetwork Object

  • Connect to and disconnect from network shares and network printers

  • Map and unmap network shares

  • Access information about the currently logged-on user


WshController Object

Create a remote script process using the Controller method CreateScript()


WshRemote Object

  • Remotely administer computer systems on a computer network

  • Programmatically manipulate other programs/scripts


WshRemoteError Object

Access the error information available when a remote script (a WshRemote object) terminates as a result of a script error


WshShell Object

  • Run a program locally

  • Manipulate the contents of the registry

  • Create a shortcut

  • Access a system folder

  • Manipulate environment variables (such as WINDIR, PATH, or PROMPT)


WshShortcut Object

Programmatically create a shortcut


WshSpecialFolders Object

Access any of the Windows Special Folders


WshUrlShortcut Object

Programmatically create a shortcut to an Internet resource


WshEnvironment Object

Access any of the environment variables (such as WINDIR, PATH, or PROMPT)


WshScriptExec Object

Determine status and error information about a script run with Exec()

Access the StdIn, StdOut, and StdErr channels

In addition to the object interfaces provided by Windows Script Host, administrators can use any ActiveX control that exposes automation interfaces to perform various tasks on the Windows platform. For example, administrators can write scripts to manage the Windows Active Directory Service Interface (ADSI).

Date

History

Reason

April 2009

Added links to listed objects.

Customer feedback.

Community Additions

Show:

Inherited

Protected

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 .

Аннотация: Рассматриваются основные объекты, поддерживаемые WSH (WScript, WshShell, WshEnvironment, WshSpecialFolders, WshArguments). Даются примеры сценариев для работы со стандартными объектами WSH

Собственная объектная модель WSH

Перейдем к описанию собственной объектной модели Windows Script Host. С помощью внутренних объектов WSH из сценариев можно выполнять следующие основные задачи:

  • выводить информацию в стандартный выходной поток (на экран) или в диалоговое окно Windows;
  • читать данные из стандартного входного потока (то есть вводить данные с клавиатуры) или использовать информацию, выводимую другой командой;
  • использовать свойства и методы внешних объектов, а также обрабатывать события, которые генерируются этими объектами;
  • запускать новые независимые процессы или активизировать уже имеющиеся;
  • запускать дочерние процессы с возможностью контроля их состояния и доступа к их стандартным входным и выходным потокам;
  • работать с локальной сетью: определять имя зарегистрировавшегося пользователя, подключать сетевые диски и принтеры;
  • просматривать и изменять переменные среды;
  • получать доступ к специальным папкам Windows;
  • создавать ярлыки Windows;
  • работать с системным реестром.

В WSH версии 5.6 (стандартная версия в Windows XP) входят перечисленные ниже объекты:

  • WScript. Это главный объект WSH, который служит для создания других объектов или связи с ними, содержит сведения о сервере сценариев, а также позволяет вводить данные с клавиатуры и выводить информацию на экран или в окно Windows.
  • WshArguments. Обеспечивает доступ ко всем параметрам командной строки запущенного сценария или ярлыка Windows.
  • WshNamed. Обеспечивает доступ к именным параметрам командной строки запущенного сценария.
  • WshUnnamed. Обеспечивает доступ к безымянным параметрам командной строки запущенного сценария.
  • WshShell. Позволяет запускать независимые процессы, создавать ярлыки, работать с переменными среды, системным реестром и специальными папками Windows.
  • WshSpecialFolders. Обеспечивает доступ к специальным папкам Windows.
  • WshShortcut. Позволяет работать с ярлыками Windows.
  • WshUrlShortcut. Предназначен для работы с ярлыками сетевых ресурсов.
  • WshEnvironment. Предназначен для просмотра, изменения и удаления переменных среды.
  • WshNetwork. Используется при работе с локальной сетью: содержит сетевую информацию для локального компьютера, позволяет подключать сетевые диски и принтеры.
  • WshScriptExec. Позволяет запускать консольные приложения в качестве дочерних процессов, обеспечивает контроль состояния этих приложений и доступ к их стандартным входным и выходным потокам.
  • WshController. Позволяет запускать сценарии на удаленных машинах.
  • WshRemote. Позволяет управлять сценарием, запущенным на удаленной машине.
  • WshRemoteError. Используется для получения информации об ошибке, возникшей в результате выполнения сценария, запущенного на удаленной машине.

Кроме этого, имеется объект FileSystemObject, обеспечивающий доступ к файловой системе компьютера (этот объект будет подробно рассмотрен в следующей лекции).

Рассмотрим более подробно несколько объектов WSH, которые часто используются в сценариях.

Объект WScript

Свойства объекта WScript позволяют получить полный путь к использующемуся серверу сценариев (wscript.exe или cscript.exe), параметры командной строки, с которыми запущен сценарий, режим его работы (интерактивный или пакетный). Кроме этого, с помощью свойств объекта WScript можно выводить информацию в стандартный выходной поток и читать данные из стандартного входного потока. Также WScript предоставляет методы для работы внутри сценария с объектами автоматизации и вывода информации на экран (в текстовом режиме) или в окно Windows.

Отметим, что в сценарии WSH объект WScript можно использовать сразу, без какого-либо предварительного описания или создания, так как его экземпляр создается сервером сценариев автоматически. Для использования же всех остальных объектов нужно использовать либо метод CreateObject, либо определенное свойство другого объекта.

Свойства объекта WScript представлены в табл. 5.1.

Таблица
5.1.
Свойства объекта WScript

Свойство Описание
Application Предоставляет интерфейс Idispatch для объекта WScript
Arguments Содержит указатель на коллекцию WshArguments, содержащую параметры командной строки для исполняемого сценария
FullName Содержит полный путь к исполняемому файлу сервера сценариев (в Windows XP обычно это C:WINDOWSSYSTEM32CSCRIPT.EXE или C:WINDOWSSYSTEM32WSCRIPT.EXE)
Name Содержит название объекта Wscript (Windows Script Host)
Path Содержит путь к каталогу, в котором находится cscript.exe или wscript.exe (в Windows XP обычно это C:WINDOWSSYSTEM32)
ScriptFullName Содержит полный путь к запущенному сценарию
ScriptName Содержит имя запущенного сценария
StdErr Позволяет запущенному сценарию записывать сообщения в стандартный поток для ошибок
StdIn Позволяет запущенному сценарию читать информацию из стандартного входного потока
StdOut Позволяет запущенному сценарию записывать информацию в стандартный выходной поток
Version Содержит версию WSH

Опишем более подробно некоторые свойства объекта WScript.

Свойство Arguments

В следующем примере (листинг 5.1) с помощью цикла For Each … Next на экран выводятся все параметры командной строки, с которыми был запущен сценарий.

'********************************************************************
' Имя: Args.vbs                                                   
' Язык: VBScript                                                    
' Описание: Работа с аргументами запущенного сценария              
'********************************************************************
Option Explicit

Dim s,objArgs,Arg 
Set objArgs = WScript.Arguments  ' Создаем объект WshArguments
For Each Arg In objArgs
  s=s & Arg ' Формируем строки со значениями аргументов
Next

WScript.Echo s   ' Выводим сформированные строки
'*************  Конец *********************************************


Листинг
5.1.
Вывод всех параметров командной строки сценария (VBScript)

Свойства StdErr, StdIn, StdOut

Доступ к стандартным входным и выходным потокам с помощью свойств StdIn, StdOut и StdErr можно получить только в том случае, если сценарий запускался в консольном режиме с помощью cscript.exe. Если сценарий был запущен с помощью wscript.exe, то при попытке обратиться к этим свойствам возникнет ошибка «Invalid Handle».

Работать с потоками StdOut и StdErr можно с помощью методов Write, WriteLine, WriteBlankLines, а с потоком StdIn — с помощью методов Read, ReadLine, ReadAll, Skip, SkipLine. Эти методы кратко описаны в табл. 5.2.

Таблица
5.2.
Методы для работы с потоками

Метод Описание
Read(n) Считывает из потока StdIn заданное параметром n число символов и возвращает полученную строку
ReadAll() Читает символы из потока StdIn до тех пор, пока не встретится символ конца файла ASCII 26 (<Ctrl>+<Z>), и возвращает полученную строку
ReadLine() Возвращает строку, считанную из потока StdIn
Skip(n) Пропускает при чтении из потока StdIn заданное параметром n число символов
SkipLine() Пропускает целую строку при чтении из потока StdIn
Write(string) Записывает в поток StdOut или StdErr строку string (без символа конца строки)
WriteBlankLines(n) Записывает в поток StdOut или StdErr заданное параметром n число пустых строк
WriteLine(string) Записывает в поток StdOut или StdErr строку string (вместе с символом конца строки)

Напомним, что операционная система Windows поддерживает механизм конвейеризации (символ «|» в командной строке). Этот механизм делает возможным передачу данных от одной программы к другой. Таким образом, используя стандартные входные и выходные потоки, можно из сценария обрабатывать строки вывода другого приложения или перенаправлять выводимые сценарием данные на вход программ-фильтров ( FIND или SORT ). Например, следующая команда будет сортировать строки вывода сценария example.js и выводить их в файл sort.txt:

cscript //Nologo example.js | sort > sort.txt

Опция //Nologo здесь нужна для того, чтобы в файл sort.txt не попадали строки с информацией о разработчике и номере версии WSH.

Кроме этого, с помощью методов, работающих с входным потоком StdIn, можно организовывать диалог с пользователем, то есть создавать интерактивные сценарии. Соответствующий пример приведен в листинге 5.2.

'*******************************************************************
'* Имя: Interact.vbs                                               
'* Язык: VBScript                                                  
'* Описание: Ввод/вывод строк в консольном режиме                  
'*******************************************************************
Dim  s
' Выводим строку на экран
WScript.StdOut.Write "Введите число: "
' Считываем строку
s = WScript.StdIn.ReadLine
' Выводим строку на экран
WScript.StdOut.WriteLine "Вы ввели число " & s
'*************  Конец *********************************************


Листинг
5.2.
Ввод/вывод строк в символьном режиме

Downloads
4608.zip

Windows Scripting Host (WSH) fills a long-standing gap for batch file processing that has existed since Microsoft first released Windows 3.1. In the past, if you wanted to automate Windows applications, you had to use batch files with the command processor or use the Macro Recorder. Both methods have disadvantages. Batch files are character-based and not well integrated into the graphical environment. The Macro Recorder lacks advanced program flow control and is notorious for sending keystrokes and mouse clicks to the wrong windows if the slightest unexpected variation changes the desktop’s or the application’s focus.

Fortunately, WSH now provides the native Win32-based scripting that was lacking. WSH lets you write scripts that automate common tasks, perform logons, read and write to the Registry, and launch and control Windows applications.

In this article, I’ll first introduce you to WSH and to the WSH object model. I’ll then show you two examples of how to use WSH to query and display your system’s network values. Finally, I’ll show you how to use WSH’s support for component object model (COM) to run and control Microsoft Excel.

Welcome to the World of WSH

Microsoft includes WSH with Windows 98 and Internet Explorer (IE) 3.0 and higher. Microsoft will also include WSH with Windows 2000 (Win2K—formerly Windows NT 5.0). You can download the most recent WSH scripting engine from http://www.microsoft.com/msdownload/vbscript/scripting.asp. Although Microsoft supplies the WSH scripting engine, the company doesn’t provide a development environment or source editor. However, you can create WSH scripts using any standard text editor, such as Microsoft Notepad.

WSH lets you run either Visual Basic Script (VBScript) or JScript source files. Running WSH scripts is simple. You just double-click a file that has an extension of .vbs (for VBScript) or .js (for JScript). WSH automatically runs wscript.exe, the Windows version of the WSH scripting engine, using the source code from the selected file. You can also run the command-line version of WSH by executing cscript.exe from the command line or by including the cscript.exe line in a batch file. The cscript.exe version lets you use the /B parameter to turn off error messages and prompts.

When running wscript.exe or cscript.exe, you must include the name of the source file that you want to execute (e.g., myscript.vbs) as the first parameter. For example, for wscript.exe, type

wscript myscript.vbs

For cscript.exe, type

cscript myscript.vbs

WSH executes VBScript and JScript files interactively, so it doesn’t support compiling the scripts into stand-alone executable programs. However, both VBScript and JScript are full-featured programming languages with functionality that far exceeds that of batch files or recorded macros. Both scripting languages can declare variables, provide program flow using If…Then…Else and Do…Loop statements, and perform conditional logic using select statements. The languages also provide a variety of mathematical functions, from addition and multiplication to square root, sine, cosine, and exponentiation. The built-in WSH scripting objects provide support for graphical I/O, file system calls, and Registry access.

The WSH Object Model

Before you start writing WSH scripts, you need to be familiar with the WSH object model. The three main objects are WScript, WshShell, and WshNetwork. The descriptions that follow provide only basic information about these objects. For detailed information, you can download the «Windows Script Host Programmer’s Reference.» Go to http://msdn.microsoft.com/scripting, select Windows Scripting Host in the navigational menu on the left, click Documentation in the window that appears, and click Technical Paper.

WScript is the primary object in the WSH object model. This object has five methods (CreateObject, DisconnectObject, Echo, GetObject, and Quit) and eight properties (Application, Arguments, FullName, Name, Path, ScriptFullName, ScriptName, and Version). WScript’s main method is CreateObject, which lets you create other COM objects. The Echo method is also important, because you can use it to send output to a window. One of the most useful properties is Arguments, because it lets you work with parameters originating from the command line.

WshShell has seven methods (CreateShortcut, ExpandEnvironmentStrings, Popup, RegDelete, RegRead, RegWrite, and Run) and two properties (Environment and SpecialFolders). With WshShell’s Run method, you can launch other Windows applications. The object’s RegDelete, RegRead, and RegWrite methods let your script read and write to the Registry.

WshNetwork’s seven methods (AddPrinterConnection, EnumNetworkDrives, EnumPrinterConnections, MapNetworkDrive, RemoveNetworkDrive, RemovePrinterConnection, and SetDefaultPrinter) provide support for various network objects. For example, you can enumerate network resources and connect or disconnect network drives. With WshNetwork’s three properties (ComputerName, UserDomain, and UserName), you can retrieve computer names, users’ domain names, and the names of the users who are logged on.

In addition to WScript, WshShell, and WshNetwork, another important object you need to be familiar with is the FileSystemObject, which is part of the Scripting object model. (Both VBScript and JScript follow this model.) FileSystemObject lets your WSH scripts work with OS files and folders. This object has one property (Drives) and 24 methods. Some object methods (e.g., CopyFile, CopyFolder, DeleteFile, DeleteFolder, GetFolder, MoveFile, MoveFolder) let you manipulate files and folders; others let you append a name to an existing path (BuildPath) or open an existing text file (OpenTextFile) so that your script can read and write to the text file. (For a complete list of the FileSystemObject’s methods, go to http://premium.microsoft.com/msdn/library/tools/vbscript/htm/vsobjfilesystemm
.htm.)

Make a WSH
Now that you’ve had an overview of the WSH object framework, I’ll show you how to make a simple WSH script to display your system’s computer name, domain name, and username. Listing 1 contains the example script NetNames.vbs, which uses VBScript to create and manipulate the WshNetwork object. (The NetNames.vbsscript, complete with commentary, and the other scripts discussed in this article are available for download from the Win32 Scripting Journal Web site at http://www.winntmag.com/newsletter/scripting.)

As in standard VB, you begin the script by declaring VBScript variables using a Dim statement. However, implementing VBScript is easier than implementing VB, because you don’t need to declare a data type. In this case, the Dim statement declares the variable, oWshNetwork. The prefix o specifies an object. (Another naming convention that you might see for object is the prefix obj.)

Next, use VBScript’s Set statement with the WScript’s CreateObject method (WScript.CreateObject) to assign an instance of the WshNetwork object to the oWshNetwork variable. When you assign an instance, you’re creating a reference between the existing object and the variable you’re creating. (To conserve system memory and resources, VBScript creates references to objects rather than making copies of them.) The information in parentheses after WScript.CreateObject specifies the COM class name («WScript.Network») of the WshNetwork object. You must enclose such class names in quotes.

Now use WScript’s Echo method (WScript.Echo) to display a pop-up window that first lists the heading Computer Name: followed by your computer’s name, which the script retrieves from WshNetwork’s ComputerName property. The carriage-return line-feed character (vbCrLf) tells the script to make a hard return, and the underscore ( _ ) tells the script that the command continues on the next line. On the next line, the window displays the heading Domain Name: followed by your domain’s name, which the script retrieves from WshNetwork’s UserDomain property. Once again, vbCrLf & _ tells the script to make a hard return and to continue. On the last line, the window displays the heading Logon Name: followed by your username, which the script retrieves from WshNetwork’s UserName property. You need to enclose the headings in quotation marks, because they are strings with embedded spaces.

End the script by setting oWshNetwork to Nothing to remove the reference between this variable and the existing object. Removing the reference lets the system reallocate the memory and resources.

As you can see, the WSH and VBScript development environment is similar to that of VB. However, VBScript is easier to use because WSH’s built-in objects provide easy access to system information.

Debug Stops Here

You’ve seen a simple example of WSH in action, so let’s take a look at an example that’s a bit more complex. The example script ListFiles.vbs in Listing 2 shows how you can launch the WSH script debugger. The example also shows you how to use a collection object to list all the files in a directory and display them in a pop-up window. A collection object is a group or set of related objects. For instance, the Files collection object, which you’ll use later, is a group of File objects in which each File object represents an OS file in a folder.

Begin ListFiles.vbs by declaring the script’s variables with Dim statements. The prefix s in Dim sFileList specifies that the variable is a string data type. (Another naming convention that you might see for string is the prefix str.) Next, use WScript’s CreateObject method to create an instance of the Scripting.FileSystemObject and assign it to the oFileSystemObject variable using VBScript’s Set statement.

After creating oFileSystemObject, insert the Stop statement. When you run ListFiles.vbs, the script will stop at this point and launch the WSH script debugger. (For more information about the debugger, see the sidebar «The WSH Script Debugger,» page 9.)

Next, create a new Folders object (oFolders) that represents the /temp folder: Use the FileSystemObject’s GetFolder method to return a Folder object that corresponds to the folder at the path «c:temp». Each folder or subdirectory can contain multiple files; the Files collection in oFolders represents the files that the c:temp folder contains. Use VBScript’s For Each…Next statement to loop through the collection of file objects in the oFolder.Files collection. Append sFileList with each file object’s name followed by vbCrLf so that each filename is on a separate line. Use WScript’s Echo method to display sFileList in a pop-up window. Finally, set oFileSystemObject, oFolder, and oFile to Nothing.

Calling all COMs
With WSH, you can programmatically control any Windows application that supports Object Linking and Embedding (OLE) automation. WSH’s ability to execute and control Windows applications with COM objects raises the functionality bar far higher than simple batch files do. Most major Windows applications, including all Microsoft Office applications, expose rich functionality through their respective COM object models. You can then use a COM-enabled development environment such as WSH with VBScript to access that functionality. For example, Listing 3 contains a script, NetDrives.vbs, that launches Excel and uses WSH’s COM support to write all the mapped network drives to cells in a worksheet.

I recommend that you begin NetDrives.vbs (or any script that’s more than a few lines long) with VBScript’s Option Explicit statement. This statement requires that you declare all variables before using them. Like VB, VBScript doesn’t require that you declare variables. At first, this feature might seem convenient, but you can introduce subtle bugs in your scripts if you don’t declare variables. For example, if you declare a variable named nCount, which you intend to use as a loop counter, but you inadvertently use ncount (no capitalization) in the code, VBScript treats ncount as a separate variable, which can cause unpredictable results. Worse yet, this type of error is often difficult to track down. The Option Explicit statement prevents this type of problem.

After you use the Option Explicit statement, declare the script’s working variables and initialize the nCount loop counter to 1. The prefix n in nCount specifies that the variable is numeric. Then, create an instance of the WshNetwork object and assign it to the oWshNetwork variable. Next, use WshNetwork’s EnumNetworkDrives method (oWshNetwork.EnumNetworkDrives) to return a collection containing network drive mappings. Assign this collection to the oNetDrives variable.

Now you must manipulate objects from Excel’s COM object model. In NetDrives.vbs, you use Excel’s top-level Application object and three of its children: the Workbooks collection object, Range object, and Cells collection object. You’ll be using the Application object’s Visible property, which controls whether users can see an object such as a worksheet or workbook. If you specify True, users can see the object; if you specify False, they can’t see it. The Workbooks collection object is a set of Workbook objects, each of which represents a workbook in Excel. The Range object represents a cell, row, or group of cells in a worksheet. The Cells collection object is a set of Cell objects, each of which represents one cell in a worksheet. (For information about these and other Excel objects, check out Chapters 2 and 4 of the Microsoft Office 97/Visual Basic Programmer’s Guide at http://www.microsoft.com/officedev/articles/opg/toc/pgtoc.htm.)

To access the Application object, use WScript’s CreateObject method to create an instance of the Excel.Application object, assigning it to the oXL variable. Next, set oXL’s Visible property to True to display the Excel application to users. Use the Workbooks collection object’s Add method to add a new workbook. You don’t need to set the return value of the workbook to an object variable because you aren’t working with the object’s methods or properties. However, if you want to work with the methods or properties, you need to set the return value.

The workbook you just added contains a default worksheet. Each member of the Cells collection object represents a cell in the worksheet. For example, Cells(1, 1) represents cell A1 and Cells(2, 1) represents cell A2. Because you initialized nCount to 1, oXL.Cells(nCount, 1) is Cells(1, 1). You use the Range object’s Value property to assign Cells(1, 1) to «Mapped Network Drives».

After setting up the worksheet, use VBScript’s For Each…Next statement to iterate through the oNetDrives collection. The nCount counter increments each oNetDrive object (i.e., each network drive mapping) and tells the script which cell to place the drive mapping in. The For Each…Next loop ends when the script reads the last member of the oNetDrives collection. Screen 1 contains example output from this script.

You might have noticed much similarity between the way that you created the Excel.Application object and the way you created the Scripting.FileSystemObject and WScript.Network objects in the previous examples. The reason for this similarity is that COM is the mechanism WSH uses to create and use all of these objects.

If You’re WSHing for More

WSH provides the long-overdue scripting engine for the Win32 platform. The WSH scripting object model and VBScript combine to make a powerful ally to take on your Win32 scripting challenges. This article is only an introduction to WSH’s wide-ranging capabilities. You can find out more about WSH on Microsoft’s Web site at http://msdn.microsoft.com/scripting.

Аннотация: Рассматриваются основные объекты, поддерживаемые WSH (WScript, WshShell, WshEnvironment, WshSpecialFolders, WshArguments). Даются примеры сценариев для работы со стандартными объектами WSH

Собственная объектная модель WSH

Перейдем к описанию собственной объектной модели Windows Script Host. С помощью внутренних объектов WSH из сценариев можно выполнять следующие основные задачи:

  • выводить информацию в стандартный выходной поток (на экран) или в диалоговое окно Windows;
  • читать данные из стандартного входного потока (то есть вводить данные с клавиатуры) или использовать информацию, выводимую другой командой;
  • использовать свойства и методы внешних объектов, а также обрабатывать события, которые генерируются этими объектами;
  • запускать новые независимые процессы или активизировать уже имеющиеся;
  • запускать дочерние процессы с возможностью контроля их состояния и доступа к их стандартным входным и выходным потокам;
  • работать с локальной сетью: определять имя зарегистрировавшегося пользователя, подключать сетевые диски и принтеры;
  • просматривать и изменять переменные среды;
  • получать доступ к специальным папкам Windows;
  • создавать ярлыки Windows;
  • работать с системным реестром.

В WSH версии 5.6 (стандартная версия в Windows XP) входят перечисленные ниже объекты:

  • WScript. Это главный объект WSH, который служит для создания других объектов или связи с ними, содержит сведения о сервере сценариев, а также позволяет вводить данные с клавиатуры и выводить информацию на экран или в окно Windows.
  • WshArguments. Обеспечивает доступ ко всем параметрам командной строки запущенного сценария или ярлыка Windows.
  • WshNamed. Обеспечивает доступ к именным параметрам командной строки запущенного сценария.
  • WshUnnamed. Обеспечивает доступ к безымянным параметрам командной строки запущенного сценария.
  • WshShell. Позволяет запускать независимые процессы, создавать ярлыки, работать с переменными среды, системным реестром и специальными папками Windows.
  • WshSpecialFolders. Обеспечивает доступ к специальным папкам Windows.
  • WshShortcut. Позволяет работать с ярлыками Windows.
  • WshUrlShortcut. Предназначен для работы с ярлыками сетевых ресурсов.
  • WshEnvironment. Предназначен для просмотра, изменения и удаления переменных среды.
  • WshNetwork. Используется при работе с локальной сетью: содержит сетевую информацию для локального компьютера, позволяет подключать сетевые диски и принтеры.
  • WshScriptExec. Позволяет запускать консольные приложения в качестве дочерних процессов, обеспечивает контроль состояния этих приложений и доступ к их стандартным входным и выходным потокам.
  • WshController. Позволяет запускать сценарии на удаленных машинах.
  • WshRemote. Позволяет управлять сценарием, запущенным на удаленной машине.
  • WshRemoteError. Используется для получения информации об ошибке, возникшей в результате выполнения сценария, запущенного на удаленной машине.

Кроме этого, имеется объект FileSystemObject, обеспечивающий доступ к файловой системе компьютера (этот объект будет подробно рассмотрен в следующей лекции).

Рассмотрим более подробно несколько объектов WSH, которые часто используются в сценариях.

Объект WScript

Свойства объекта WScript позволяют получить полный путь к использующемуся серверу сценариев (wscript.exe или cscript.exe), параметры командной строки, с которыми запущен сценарий, режим его работы (интерактивный или пакетный). Кроме этого, с помощью свойств объекта WScript можно выводить информацию в стандартный выходной поток и читать данные из стандартного входного потока. Также WScript предоставляет методы для работы внутри сценария с объектами автоматизации и вывода информации на экран (в текстовом режиме) или в окно Windows.

Отметим, что в сценарии WSH объект WScript можно использовать сразу, без какого-либо предварительного описания или создания, так как его экземпляр создается сервером сценариев автоматически. Для использования же всех остальных объектов нужно использовать либо метод CreateObject, либо определенное свойство другого объекта.

Свойства объекта WScript представлены в табл. 5.1.

Таблица
5.1.
Свойства объекта WScript

Свойство Описание
Application Предоставляет интерфейс Idispatch для объекта WScript
Arguments Содержит указатель на коллекцию WshArguments, содержащую параметры командной строки для исполняемого сценария
FullName Содержит полный путь к исполняемому файлу сервера сценариев (в Windows XP обычно это C:\WINDOWS\SYSTEM32\CSCRIPT.EXE или C:\WINDOWS\SYSTEM32\WSCRIPT.EXE)
Name Содержит название объекта Wscript (Windows Script Host)
Path Содержит путь к каталогу, в котором находится cscript.exe или wscript.exe (в Windows XP обычно это C:\WINDOWS\SYSTEM32)
ScriptFullName Содержит полный путь к запущенному сценарию
ScriptName Содержит имя запущенного сценария
StdErr Позволяет запущенному сценарию записывать сообщения в стандартный поток для ошибок
StdIn Позволяет запущенному сценарию читать информацию из стандартного входного потока
StdOut Позволяет запущенному сценарию записывать информацию в стандартный выходной поток
Version Содержит версию WSH

Опишем более подробно некоторые свойства объекта WScript.

Свойство Arguments

В следующем примере (листинг 5.1) с помощью цикла For Each … Next на экран выводятся все параметры командной строки, с которыми был запущен сценарий.

'********************************************************************
' Имя: Args.vbs                                                   
' Язык: VBScript                                                    
' Описание: Работа с аргументами запущенного сценария              
'********************************************************************
Option Explicit

Dim s,objArgs,Arg 
Set objArgs = WScript.Arguments  ' Создаем объект WshArguments
For Each Arg In objArgs
  s=s & Arg ' Формируем строки со значениями аргументов
Next

WScript.Echo s   ' Выводим сформированные строки
'*************  Конец *********************************************


Листинг
5.1.
Вывод всех параметров командной строки сценария (VBScript)

Свойства StdErr, StdIn, StdOut

Доступ к стандартным входным и выходным потокам с помощью свойств StdIn, StdOut и StdErr можно получить только в том случае, если сценарий запускался в консольном режиме с помощью cscript.exe. Если сценарий был запущен с помощью wscript.exe, то при попытке обратиться к этим свойствам возникнет ошибка «Invalid Handle».

Работать с потоками StdOut и StdErr можно с помощью методов Write, WriteLine, WriteBlankLines, а с потоком StdIn — с помощью методов Read, ReadLine, ReadAll, Skip, SkipLine. Эти методы кратко описаны в табл. 5.2.

Таблица
5.2.
Методы для работы с потоками

Метод Описание
Read(n) Считывает из потока StdIn заданное параметром n число символов и возвращает полученную строку
ReadAll() Читает символы из потока StdIn до тех пор, пока не встретится символ конца файла ASCII 26 (<Ctrl>+<Z>), и возвращает полученную строку
ReadLine() Возвращает строку, считанную из потока StdIn
Skip(n) Пропускает при чтении из потока StdIn заданное параметром n число символов
SkipLine() Пропускает целую строку при чтении из потока StdIn
Write(string) Записывает в поток StdOut или StdErr строку string (без символа конца строки)
WriteBlankLines(n) Записывает в поток StdOut или StdErr заданное параметром n число пустых строк
WriteLine(string) Записывает в поток StdOut или StdErr строку string (вместе с символом конца строки)

Напомним, что операционная система Windows поддерживает механизм конвейеризации (символ «|» в командной строке). Этот механизм делает возможным передачу данных от одной программы к другой. Таким образом, используя стандартные входные и выходные потоки, можно из сценария обрабатывать строки вывода другого приложения или перенаправлять выводимые сценарием данные на вход программ-фильтров ( FIND или SORT ). Например, следующая команда будет сортировать строки вывода сценария example.js и выводить их в файл sort.txt:

cscript //Nologo example.js | sort > sort.txt

Опция //Nologo здесь нужна для того, чтобы в файл sort.txt не попадали строки с информацией о разработчике и номере версии WSH.

Кроме этого, с помощью методов, работающих с входным потоком StdIn, можно организовывать диалог с пользователем, то есть создавать интерактивные сценарии. Соответствующий пример приведен в листинге 5.2.

'*******************************************************************
'* Имя: Interact.vbs                                               
'* Язык: VBScript                                                  
'* Описание: Ввод/вывод строк в консольном режиме                  
'*******************************************************************
Dim  s
' Выводим строку на экран
WScript.StdOut.Write "Введите число: "
' Считываем строку
s = WScript.StdIn.ReadLine
' Выводим строку на экран
WScript.StdOut.WriteLine "Вы ввели число " & s
'*************  Конец *********************************************


Листинг
5.2.
Ввод/вывод строк в символьном режиме

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 is shown in Figure 7.1. It is a small and fairly shallow object model
that consists of a single application-level object, the WScript
object, along with two additional levels of child objects.

The Windows Scripting Host object model

Figure 7-1.  The Windows Scripting Host object model

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 …

  • Windows script host ошибка компиляции microsoft jscript
  • Windows sdk что это за программа
  • Windows run cmd as admin
  • Windows script host ошибка выполнения microsoft vbscript
  • Windows scan app windows 10