Sunday, April 15, 2012

WScript Object

Windows supports two methods of starting scripts. The CScript application works at the command prompt, while the WScript application works from within the graphical user environment. Both applications accomplish the same task—they provide a means for interpreting a script file you create.

CScript and WScript use the same command line. You must provide a script name as the first command line argument. Most scripts have a VBE or JS file extension, but any extension is acceptable. For example, you can still use VBS files with Windows Scripting Host (WSH), but the icon won’t look right, in some cases, and you can’t double-click it to start the execution with newer Windows products.



The VBS extension is the right choice for older versions of Windows. The icon is yellow for VBE files and blue for JS files. These utilities use the following syntax:

CScript [] []
WScript [] []



The following list describes each of the command line arguments:

//? Displays the currently documented command line switches. The newest versions of WSH tend to reject older switches, even those of the undocumented variety.

//B Limits user interaction with the script. Batch mode suppresses all non–command line console user interface requests from the script. It also suppresses error message display (a change from previous versions).

//D Activates debugging mode so you can fix errors in a script.

//H:CScript Makes CSCRIPT.EXE the default application for running scripts. (WScript is the default engine.)

//H:WScript Makes WSCRIPT.EXE the default application for running scripts.

//I Allows full interaction with the user. Any pop-up dialog boxes will wait for user input
before the script continues.

//Job: JobName Executes a WSH job. A WSH job has a Windows Script File (WSF) extension.
This file enables you to perform tasks using multiple scripting engines and multiple files. Essentially, this allows you to perform a “super batch” process. Creating WSF files is an advanced technique not discussed in this book because it isn’t very useful in most cases. You can learn more about this topic at
http://msdn.microsoft.com/archive/en-us/wsh/htm/wsAdvantagesOfWs.asp

//Logo and //NoLogo WSH normally prints out a logo message. You’d use the //NoLogo switch to prevent WSH from displaying this message.

//S: This command line switch allows you to save current command line options for a user.
WSH will save the following options://B,//I,//Logo,//Nologo, and//T:n.

//T:TimeLimit Limits the maximum time the script can run to the number of seconds specified. Normally, there isn’t any timeout value. You’d use this switch in situations where a script might end up in a continuous loop or is unable to get the requested information for other reasons. For example, you might use this switch when requesting information on a network drive.

//X Starts the script in the debugger. This allows you to trace the execution of the script from
beginning to end.

//U Outputs any console information using Unicode instead of pure ASCII. You use this switch on systems where you need to support languages other than English. This is a CScriptonly option.

Notice that all of these command line switches start with two slashes (//) to differentiate them from switches you may need for your script. WSH passes script arguments to your script for processing. Script arguments can be anything including command line switches of your own or values needed to calculate a result.

Users of older versions of CScript and WScript may remember the //C and the //W switches used to switch the default scripting engines. Newer versions of CScript and WScript replace these switches with the //H switch.

You'll also find the //R (reregister) and //Entrypoint switches missing from WSH because script developers no longer need the functionality.

Always use the correct command line switches for the version of Windows and WSH installed on your machine. You can work with WSH in either interactive or batch mode. Use batch mode when you need to perform tasks that don’t require user input. For example, you might want to run Scan Disk every evening, but use different command line switches for it based on the day.

You could use Task Scheduler to accomplish this task, but using it in conjunction with a WSH script improves the flexibility you get when running the task.

Another kind of batch processing might be to send log files to your supervisor or perhaps set up a specific set of environment variables for a character-mode application based on the current user. On the other hand, interactive mode requires user interaction.

You’d use it for tasks such as cleaning the hard drive because you don’t always know whether the user needs a particular file.

Such a script could ask the user a set of general questions, and then clean excess files from the hard drive based on the user input. The cleaning process would follow company guidelines and save the user time.

Because batch processing doesn't require any form of user input, it’s usually a good idea to include the //T switch with the //B switch. This combination stops the script automatically if it runs too long. In most cases, using this switch setup stops an errant script before it corrupts the Windows environment or freezes the machine. However, you can't time some tasks with ease.

For example, any Web-based task is difficult to time because you can't account for problems with a slow connection. In this case, you'll need to refrain from using the //T switch or provide a worst-case scenario time interval.

The next set of command line switches to consider is //Logo and //NoLogo . There isn’t any right or wrong time to use these switches, but you usually use the //Logo switch when testing a script and the
//NoLogo switch afterward. The reason is simple.

During the testing process, you want to know about every potential source of problems in your script environment, including an old script engine that might cause problems. On the other hand, you don’t want to clutter your screen with useless text after you debug the script. Using the //NoLogo switch keeps screen clutter to a minimum.

The WScript object is the root object of the Windows Script Host object model hierarchy. It never needs to be instantiated before invoking its properties and methods, and it is always available from any script file. The WScript object provides access to information such as:

command-line arguments,

the name of the script file,

the host file name,

and host version information.

The WScript object allows you to:

create objects,

connect to objects,

disconnect from objects,

sync events,

stop a script's execution programmatically,

output information to the default output device (either a Windows dialog box or the command console).

The WScript object can be used to set the mode in which the script runs (either interactive or batch).

The WScript object is directly available to all scripts being executed by wscript or cscript and represents the currently running instance of the scripting host executable (wscript or cscript). The WScript object cannot be instantiated directly using CreateObject, however scripts running under WSH can obtain a reference to it via the Application property.

Through the WScript object one can gain access to WSH version information, the paths to the host executable and the script currently being executed, any arguments passed to the script, and the standard input, output and error streams. In addition, the WScript object can be used to instantiate, obtain references to, and bind to COM components. Methods and properties are also available to alter the script timeout values, and to cause the script to sleep for a specified period of time.

PROPERTIES

Application Property
The Application property is read only and returns a reference to the current WScript instance.

Syntax: WScript.Application

BuildVersion Property
The BuildVersion property is read only and returns a Long value which is the build version number of the host executable file (cscript or wscript).

Syntax: WScript.BuildVersion

FullName Property
The FullName property returns the full path to the host executable file (cscript or wscript). This property is read only.

Syntax: WScript.FullName

Interactive Property
The Interactive property returns a Boolean that indicates whether or not the host executable file (cscript or wscript) was invoked in interactive mode. This property is read/write and can be used to change the mode of the currently executing script at runtime. When this property is False, interactive commands such as Echo, MsgBox and InputBox have no effect. The WshShell.Popup method, and the use of StdErr, StdIn and StdOut are, however, unaffected by the setting of this property.

Syntax: WScript.Interactive[ = True|False]

Name Property
The Name property is read only and returns the name of the WScript object (usually "Windows Script Host"). This is the default property of the WScript object.

Syntax: WScript[.Name]

Path Property
The Path property is read only and returns the full path to the directory containing the host executable file (wscript or cscript).

Syntax: WScript.Path

ScriptFullName Property
The ScriptFullName property is read only and returns the full path to the script currently being executed.

Syntax: WScript.ScriptFullName

ScriptName Property
The ScriptName property is read only and returns the filename of the script currently being executed.

Syntax: WScript.ScriptName

StdErr Property
The StdErr property returns a write-only TextStream object that outputs text to the Standard Error stream. This property is read only and can only be used when cscript is the host executable.

Syntax: WScript.StdErr

StdIn Property
The StdIn property returns a read-only TextStream object that reads text from the Standard Input stream. This property is read only and can only be used when cscript is the host executable.

Syntax: WScript.StdIn

StdOut Property
The StdOut property returns a write-only TextStream object that outputs text to the Standard Output stream. This property is read only and can only be used when cscript is the host executable.

Syntax: WScript.StdOut

Timeout Property
The Timeout property is used to set or get the timeout period (in seconds) for the currently executing script. The script will automatically be terminated after the number of seconds specified by this property, which is of type Long.

Syntax: WScript.Timeout[ = lngTimeout]

Version Property
The Version property is read only and returns a string that is the version number of the host executable.

Syntax: WScript.Version



COLLECTION PROPERTIES

Arguments Collection Property
The Arguments collection property is read only and returns the collection of arguments supplied when invoking the current script. The argument list does not include the name of the host executable file (cscript or wscript), or the name of the script being invoked.

Syntax: WScript.Arguments



METHODS

ConnectObject Method
The ConnectObject method binds the events of an object to event handlers (sinks) in the currently executing script.

Syntax: WScript.ConnectObject objObject, strSubPrefix

CreateObject Method
The CreateObject method creates an instance of a COM component with a specified ProgID and, optionally, registers the current script as a handler for events generated by the newly created object.

Syntax: WScript.CreateObject (strProgID, [strSubPrefix])

DisconnectObject Method
The DisconnectObject method disconnects any event-handling connection between the currently executing script and the specified object. If a connection with the specified object was not previously established with a call to ConnectObject, CreateObject or GetObject, then this method does nothing.

Syntax: WScript.DisconnectObject objObject

Echo Method
The Echo method concatenates its arguments into a space-separated string and displays this string in a Dialog Box (if invoked under wscript), or on the standard output stream (if invoked under cscript). Under cscript, a newline character is appended to the output. This method has no effect if the WScript.Interactive property is False.

Syntax: WScript.Echo [vntArg1] [,vntArg2] [,vntArg3] ...

GetObject Method
The GetObject method loads the specified file into the associated application and returns a reference to the instance of the application object. If an application object of the appropriate type already exists, the specified file will be loaded into the existing instance, otherwise a new instance will be created. If the specified file can be handled by multiple applications, the ProgID of the desired application can be specified. If an empty string is specified for the filename, a ProgID must be specified, and this method will behave the same as a call to CreateObject. The GetObject method can also be used to register the current script as an event-handler for the returned object.

Syntax: WScript.GetObject (strPathName [,strProgID] [,strSubPrefix])

Quit Method
The Quit method causes the current script to terminate and return the specified exit code.

Syntax: WScript.Quit [lngExitCode]

Sleep Method
The Sleep method causes execution of the current script to be suspended for the specified number of milliseconds.

Syntax: WScript.Sleep lngTime

No comments: