[ LiB ] |
The WSH object model provides JScript with access to Windows resources. Simply put, the WSH object model does for JScripts what the browser DOM does for JavaScripts. Instead of exposing browser objects, the WSH provides access to an assortment of Windows objects, which in turn provides access to dozens of object properties and methods that provide direct access and control over an assortment of Windows resources.
The WSH object model consists of 14 different objects. Figure 6.1 lists each of these objects and shows how they relate to one another.
The WScript object sits at the top of the WSH object model. By default, an instance of the WScript object is created automatically at script execution. Therefore, you can access all of the WScript object's properties and methods without having to first set up a reference to it. However, all of the other objects in the WSH object model must first be defined, or instantiated , before you can start working with their properties and methods.
The WScript object is sometimes referred to as a public object. In addition to the WScript object, the WSH supports three other public objects. These objects are the WshController , WshShell , and WshNetwork objects. To instantiate these other three objects, you have to use the WScript object's CreateObject() method. All the other objects that make up the WSH object model are instantiated using one of the properties or methods provided by one of the four WSH public objects. Table 6.1 lists the other 10 WSH objects and identifies the properties or methods used to instantiate them.
Object | Method of Instantiation |
---|---|
WshArguments | WScript.Arguments |
WshNamed | WScript.Arguments.Named |
WshUnnamed | WScript.Arguments.Unnamed |
WshRemote | WshController.CreateScript() |
WshRemoteError | WshRemote.Error |
WshShortcut | WshShell.CreateShortcut() |
WshUrlShortcut | WshShell.CreateShortcut() |
WshEnvironment | WshShell.Environment |
WshSpecialFolders | WshShell.SpecialFolders |
WshScriptExec | WshShell. Exec () |
Each WSH object provides access to its own collection of properties and methods. Table 6.2 provides a complete list of WSH objects and their associated properties.
Object | Description |
---|---|
WScript | This object provides access to numerous properties and methods and to the other objects that make up the WSH object model. Properties: Arguments,BuildVersion, FullName,Interactive, Name , Path ,ScriptFullName,ScriptName,StdErr,StdIn,StdOut ,and Version Methods: ConnectObject(), CreateObject() , DisconnectObject(), Echo(), GetObject(), Quit(), and Sleep() |
WshArguments | This object provides access to any command-line arguments passed to the script at the beginning of its execution. Properties: Item , and Length; Named and Unnamed Methods: Count() and ShowUsage() |
WshNamed | This object provides access to a collection of named command-line arguments. Properties: Item and Length Methods: Count() and Exists() |
WshUnnamed | This object provides access to a collection of unnamed command-line arguments. Properties: Item and Length Methods: Count() |
WshController | This object is used to set up remote script execution. Properties: This object does not support any properties. Methods: CreateScript |
WshRemote | This object provides control over the execution of remote scripts. Properties: Status and Error Methods: Execute() and Terminate() |
WshRemoteError | This object provides the capability to retrieve error information for remote scripts. Properties: Description, Line, Character, SourceText, Source , and Number Methods: This object does not support any methods. |
WshNetwork | This object provides the capability to access and manipulate network printers and drives . Properties: ComputerName, UserDomain , and UserName Methods: AddWindowsPrinterConnection(), AddPrinterConnection(), EnumNetworkDrives(), EnumPrinterConnection(), MapNetworkDrive(), RemoveNetworkDrive(), RemovePrinterConnection() , and SetDefaultPrinter() |
WshShell | This object provides the capability to access and manipulate environment variables ,Windows applications, the Windows registry, and the Windows event log. Properties: CurrentDirectory, Environment , and SpecialFolders Methods: AppActivate(), CreateShortcut(), ExpandEnvironmentStrings(), LogEvent(), Popup(), RegDelete(), RegRead(), RegWrite(), Run(), SendKeys() , and Exec() |
WshShortcut | This object provides access to properties and methods that can be used to create Windows shortcuts. Properties: Arguments, Description, FullName, Hotkey, IconLocation, RelativePath, TargetPath, WindowStyle , and WorkingDirectory Method: Save() |
WshUrlShortcut | This object provides access to properties and methods that can be used to create URL shortcuts. Properties: FullName and TargetPath Methods: Save() |
WshEnvironment | This object provides the capability to retrieve data stored in environment variables. Properties: Item and Length Methods: Remove() and Count() |
WshSpecialFolders | This object provides the capability to configure the Windows desktop, Start menu, and Quick Launch toolbar. Properties: Item, Length Methods: Count() |
WshScriptExec | This object provides access to error information generated by scripts started with the Exec() method. Properties: ExitCode, ProcessID, Status, StdOut, StdIn , and StdErr Methods: Terminate() |
Properties belonging to WSH objects provide access to information about the resources they represent. By modifying object properties, JScripts can manipulate their execution environment. Table 6.3 lists all of the properties supported by WSH objects and provides a brief description of their purposes.
Property | Description |
---|---|
Arguments | Returns the WshArguments object's arguments or sets and retrieves shortcut arguments |
AtEndOfLine | Returns either True or False , depending on whether the stream's end-of-line marker has been reached |
AtEndOfStream | Returns either True or False , depending on whether or not the end of the input stream has been reached |
BuildVersion | Retrieves the build version number for the WSH |
Character | Returns the character in a line of code where an error occurred |
Column | Returns the current column position within the input stream |
ComputerName | Returns the computer's assigned name |
CurrentDirectory | Retrieves or modifies a script's working directory |
Description | Returns a shortcut's description |
Environment | Establishes a reference to the WshEnvironment object |
Error | Exposes the WshRemoteError object in order to provide access error information |
ExitCode | Returns the exit code of a script run using Exec() |
FullName | Returns the path for the specified shortcut or executable program |
HotKey | Sets or retrieves the keystroke sequence associated with a shortcut |
IconLocation | Sets or retrieves a shortcut's icon location |
Interactive | Sets or retrieves a script execution mode |
Item | Retrieves the specified item from a collection, provides access to items stored in the WshNamed object, or retrieves an item stored in the WshUnnamed object |
Length | Returns a count of enumerated items |
Line | Returns the current line in the input stream or retrieves line number where an error occurred |
Name | Returns a text string specifying the name of the WScript object |
Number | Returns the error number associated with an error |
Path | Returns the path of the folder containing CScript and WScript execution hosts |
ProcessID | Retrieves the process ID assigned to a process started with the WshScriptExec object |
Relativepath | Sets or retrieves a relative shortcut path |
ScriptFullName | Returns the script's full path and name |
ScriptName | Returns the script's name |
Source | Identifies the object that generated a script error |
SourceText | Returns the source code responsible for creating an error |
SpecialFolders | Provides access to the Windows Start menu folder, the Windows desktop folder, and other special folders |
Status | Returns information about the execution status of a remote script |
StdErr | Provides the capability to write text to the error output stream |
StdIn | Provides the capability to read from the input stream |
StdOut | Provides the capability to write text to the output stream |
TargetPath | Returns the path for the specified shortcut |
UserDomain | Returns the name of the Windows domain of which the computer running the script is a member |
UserName | Returns the user account name of the user who is currently logged on to the computer |
Version | Returns the current version number of the WSH |
WindowStyle | Returns the specified shortcut's window style |
WorkingDirectory | Returns the specified shortcut's working directory |
NOTE
You've probably already noticed back in Table 6.2 that many objects provide access to the same properties, providing you with different ways of accessing some information.
You work with WSH object properties in pretty much the same manner that you learned how to work with object properties when writing JavaScripts. For example, the following JScript demonstrates how to access and display values assigned to properties belonging to both the WScript and WshNetwork objects.
//************************************************************ ************* //Script Name: Script 6.1.js //Author: Jerry Ford //Created: 09/12/03 //Description: This JScript shows how to access properties belonging to the //WScript and WshNetwork objects //************************************************************ ************* //Initialization Section //Instantiate the WshShell object var wshObject = WScript.CreateObject("WScript.Shell"); //Instantiate the WshNetwork object var wshNetwork = WScript.CreateObject("WScript.Network") //Main Processing Section //Call the function that displays script information DisplayScriptInfo() //Call the function that displays network information DisplayNetworkInfo() //Terminate script execution WScript.Quit() //Procedure Section //This subroutine displays script information function DisplayScriptInfo() { wshObject.Popup("Execution Environment: \t" + WScript.Name + "\r\r" + "Version: \t\t\t" + WScript.Version + "\r\r" + "Location of Execution Host: \t" +WScript.Path + "\r\r" + "Script name and path: \t" + WScript.ScriptFullname + "\r\r); } //This subroutine displays network information function DisplayNetworkInfo() { wshObject.Popup("Domain Name: \t" + wshNetwork.UserDomain + "\t\t\r\r" + "User Name: \t" + wshNetwork.UserName + "\r\r" + "Computer Name: \t" + wshNetwork.ComputerName + "\r\r); }
This script begins by first instantiating the WshShell and WshNetwork objects. Instances of both objects are established by executing the WScript object's CreateObject() method and specifying the appropriate WSH object as shown here.
var wshObject = WScript.CreateObject("WScript.Shell"); var wshNetwork = WScript.CreateObject("WScript.Network")
Once instantiated, the properties and methods associated with the WshShell object can be accessed by referencing wshObject . Likewise, the properties and methods associated with the WshNetwork object can be accessed by referring to wshNetwork .
Next , two function calls are made. The first call is made to the Display ScriptInfo() function. It uses the WshShell object's Popup() method to display a text string in a graphical pop-up dialog as shown here.
wshObject.Popup("Execution Environment: \t" + WScript.Name + "\r\r" + "Version: \t\t\t" + WScript.Version + "\r\r" + "Location of Execution Host: \t" +WScript.Path + "\r\r" + "Script name and path: \t" + WScript.ScriptFullname + "\r\r");
As you can see, the text string that is displayed consists of a number of elements, all of which are concatenated together. The information displayed by the DisplayScriptInfo() function includes the name of the scripting environment, its version number, the location of the execution host used to run the script, and the full path and name of the script itself.
NOTE
You probably noticed in the previous example the use of the \r and \t switches.These two switches provide the capability to control the formatting of text within the pop-up dialog.The \t switch equates to a tab operation, thus allowing you to pad extra spaces anywhere within the dialog.The \r switch provides the capability to perform a carriage return, allowing you to control when line breaks occur.
The second function call made by the script is to DisplayNetworkInfo() . This function uses the WScript object's Popup() method to display information stored in WshNetwork object properties. The information displayed here includes the name of the Windows domain of which the computer is a member, the name of the user who started the script, and the name of the computer running the script.
The last statement executed by the script is WScript.Quit() . This statement executes the WScript object's Quit() method. This method terminates the script's execution. Figures 6.2 and 6.3 demonstrate the output that was displayed when I ran this script.
By executing WSH object methods, your JScripts can directly affect their execution environment and manipulate the resources located within it. This includes performing such tasks as the creation and deletion of files and folders, adding and removing data to and from the Windows registry, and manipulating the Windows desktop and Start menu. Table 6.4 is a complete list of methods supported by WSH objects.
The following example demonstrates how a JScript can use WSH object methods to control Windows resources. In this case, the script uses methods belonging to the WshShell object to interact with and control the Windows Notepad application.
Method | Description |
---|---|
AddPrinterConnection() | Sets up a new printer connection to a locally installed printer using an MS-DOS printer port |
AddWindowsPrinterConnection() | Sets up a new printer connection to either a local or network printer |
AppActivate() | Activates the specified application window |
Close() | Terminates an open text stream |
ConnectObject() | Sets up a connection to a specified object |
Count | Returns the number of switches found in the WshNamed and WshUnnamed objects |
CreateObject() | Instantiates a new object reference |
CreateScript() | Instantiates a WshRemote object representing a remote script |
CreateShortcut() | Provides the capability to create new Windows shortcuts |
DisconnectObject() | Terminates a connection to the specified object |
Echo() | Displays a text string in either a pop-up dialog or the Windows command console |
EnumNetworkDrives() | Returns information about currently mapped network drives |
EnumPrinterConnections() | Returns information about current network printer connections |
Exec() | Runs an application in a child command shell and provides access to its StdIn, StdOut , and StdErr streams |
Execute() | Starts the execution of a remote script object |
Exists() | Determines whether a key exists within the WshNamed object |
ExpandEnvironmentStrings() | Retrieves an environmental variable's expanded value |
GetObject() | Returns an Automation object |
GetResource() | Returns the value of a resource as specified by the <resource> tag |
LogEvent() | Records a text string in the Windows application event log |
MapNetworkDrive() | Establishes a mapped network drive connection |
Popup() | Displays a text string in a graphical pop-up dialog |
Quit() | Terminates a script's execution |
Read() | Retrieves a string of a specified length from the input stream |
ReadAll() | Retrieves all the data currently in the input stream |
ReadLine() | Retrieves an entire line of data from the input stream |
RegDelete() | Deletes the specified registry key or value |
RegRead() | Retrieves the specified registry key or value |
RegWrite() | Creates the specified registry key or value |
Remove() | Deletes the specified environment variable |
RemoveNetworkDrive() | Removes a connection to a network drive |
RemovePrinterConnection() | Removes a connection to a network printer |
Run() | Starts a new process |
Save() | Saves the specified shortcut |
SendKeys() | Sends keystrokes to the specified window or application |
SetDefaultPrinter() | Defines the default Windows printer |
ShowUsage() | Retrieves instruction, if available, on the manner in which a script is supposed to be run |
Sign() | Adds a signature to a script that has been stored in a string. |
SignFile() | Signs or adds a digital signature to a script |
Skip() | Skips a specified number of characters when reading data from the input stream |
SkipLine() | Skips one line of data when reading from the input stream |
Sleep() | Pauses a script's execution for a specified number of seconds |
Terminate() | Stops the execution of a process started by Exec() |
Verify() | Validates the digital signature returned as a string |
VerifyFile() | Validates a digitial signature that was signed or added to a script |
Write() | Places the specified text string in the output stream |
WriteBlankLines() | Places a blank line of data in the output stream |
WriteLine() | Places the specified text string in the output stream, followed by a carriage return |
//************************************************************ ************* //Script Name: Script 6.2.js //Author: Jerry Ford //Created: 09/12/03 //Description: This JScript shows how to use methods belonging to the //WScript object in order to open Notepad and type a text string //************************************************************ ************* //Initialization Section //Instantiate the WScript Shell var wshObject = WScript.CreateObject("WScript.Shell"); //Main Processing Section //Call the function that starts the Notepad application OpenNotepad(); //Pause for 1 second before continuing PauseExecution(1000); //Call the function that writes text WriteSampleText(); //Terminate the script's execution WScript.Quit(); //Procedure Section //This subroutine Display network information function OpenNotepad() { wshObject.Run("Notepad"); } //Pause for script execution for a specified number of seconds function PauseExecution(timeLimit) { WScript.Sleep(timeLimit); } //Type a text string into the currently active application function WriteSampleText() { wshObject.SendKeys(Date() + " Daily Journal Entry"); wshObject.SendKeys("~"); wshObject.SendKeys("~"); }
This script begins by instantiating the WshShell object using the WScript object's CreateObject() method as shown here.
var wshObject = WScript.CreateObject("WScript.Shell");
Next, the script's Main Processing Section executes three function calls. The first function that is called is OpenNotepad() . It starts the Notepad application by executing the WshShell object's Run() method. The next function called is PauseExecution() , which is passed an argument of 1000 . The function takes this argument and uses it when executing the WScript object's Sleep() method. This method pauses the script's execution for a specified number of milliseconds . This allows the Notepad application time to start up before the script calls the WriteSampleText() function.
The WriteSampleText() function uses the WshShell object's Sendkeys() method to type a series of keystrokes into the Notepad application as shown here.
wshObject.SendKeys(Date() + " Daily Journal Entry"); wshObject.SendKeys("~"); wshObject.SendKeys("~");
The first of these three statements sends a text string to the Notepad application. This string consists of the current date and a small text string that have been concatenated together. The next two statements in the function emulate the Enter keystroke and result in the execution of two carriage returns. Figure 6.4 shows how the Notepad application appears on the screen after the script has run and entered its data.
[ LiB ] |