Windows Script Host (WSH)

Rough Guide to Windows Script Host

Windows Script Host (ASP)

Windows Script Host (WSH) is a scripting host for ActiveX Scripting Engines such as PerlScript. As a host, WSH enables you to use the scripting language from the command-line and from within the Windows desktop with the WSH features.

Running a WSH File

In order to execute a WSH-file, use one of two executable files depending on your needs: WScript.exe for Windows desktop files and CScript.exe is for command-line scripts. You can set the behavior and appearance of these executed scripts by running the executable without providing a file; if so, WScript will display a properties page that you can modify, and CScript will show the available switches. At work, WSH enables you to use more than one scripting engine in the same file, include typelibraries, and run more than a single job from one file to name a few.

Installing ActivePerl on Windows registers the .pls extension for use with the Windows Scripting Host.

The Object Model

Implemented as an object-model, WSH provides a simple interface for its tasks. As you author, the WSH file uses XML as its markup for separating the elements. Let's look at a simple WSH file that prints "Hello World!".

<Job ID="HelloWorld">
<script language=PerlScript>
    $WScript->Echo("Hello World!");

The XML Job-elements encloses the ID of the Job that is run, and the script elements define PerlScript as the script language to use. You will experience different results depending if you execute this from the command-line or from the windows desktop. The first instance will print text to the screen, but the Windows desktop will pop up a messagebox with "Hello World!" Next, let's look at what the WScript object has to offer.

The Windows Script Object

The WScript object is a built-in object; therefore, you do not need to create a specific instance of it within your WSH. On the contrary, the object in place is used to create instances of most other objects exposed through the WSH programming interface.

The CreateObject method will create an instance of a given object. In the following example, we'll see how an ADO Connection object is easily created within WSH.

<Job ID="ADOSample1">
<script language=PerlScript>
    $conn = $WScript->CreateObject('ADODB.Connection');

    if($conn->{State} == 1) {
        $WScript->Echo("Connection Successful!")
    else {
        $WScript->Echo("Connection Failed ...");

In addition to the above, you can specify a second parameter in the call to CreateObject. This parameter contains a string which defines a prefix that you specify. By doing so, the object's outgoing interface is connected and any time an event is fired from the object, you can intercept it within the WSH file. For example, in the ADO connection object, there are a number of events. Sparing the details, WillConnect is called before a connection starts, and Connectcomplete is called after a connection has been started. They can be easily intercepted within the WSH file.

<Job ID="Test">
<script language=PerlScript>
    $conn=$WScript->CreateObject('ADODB.Connection', 'MyWSH_');

        $WScript->Echo("Connection Successful!")
    else {

    sub MyWSH_ConnectComplete {
        $WScript->Echo("ConnectComplete was fired ... ");

    sub MyWSH_WillConnect {
        $WScript->Echo("WillConnect was fired ... ");

For the same result as above, you can use the ConnectObject-method whose syntax is $WScript->ConnectObject(Object, Prefix);. The method $WScript->DisconnectObject(Object); will disconnect its event handling provided that the object is connected. Some other methods are as follows: $Wscript->Echo(1, 2, 3, n); Print text to the standard output defined by WSH. Separating the arguments cause only a space to separate the items in a desktop environment and a newline to separate the items in a command-line scenario.

$WScript->GetObject(Pathname [,ProgID] [,Prefix]);

Retrieves an Automation object from a file or an object specified by the strProgID parameter.


Quit and process and optionally provide an integer which represents an error code.


Places the script process into an inactive state for the number of milliseconds specified and then continues execution.

And its properties are:


Provides the IDispatch interface on the WScript object


Returns a pointer to the WshArguments collection or identifies arguments for the shortcut to the collection.


Returns a string containing the full path to the host executable file or shortcut object.


Returns a string containing the friendly name of the WScript object.


Provides a string containing the name of the directory where WScript.exe or CScript.exe resides.


Provides the full path to the script currently being run.


Provides the file name of the script currently being run.


Exposes the write-only error output stream for the current script. Only applicable with CScript command-line WSH files.


Exposes the read-only input stream for the current script. CScript only.


Exposes the write-only output stream for the current script. CScript only.


Returns the version of Microsoft Windows Script Host.

On a final note, if you are using Cscript.exe and passing arguments to the file, you can read the arguments as follows:

<Job ID="args">
<script language=PerlScript>
    $arg = $WScript->{Arguments};

    $countArgs = $arg->{Count};

    for($i=0; $i<$countArgs; $i++) {

The WShShell Object

The WshShell object must be instantiated by the WScript object.

$WshShell = $WScript->CreateObject("WScript.Shell")

An interesting method of the WshShell object is the ability to activate an application window and putting it in focus. This is done by calling AppActivate either with the title in the title bar of the running application window as a parameter or by using the task ID as a parameter.

<Job Id="WshShell">
<script language=PerlScript>
    $WshShell = $WScript->CreateObject("WScript.Shell");
    $WshShell->AppActivate("Untitled - Notepad");

    my $message = "Hello from PerlScript!\n";

    for($i=0; $i < length($message); $i++) {
        $char = substr($message, $i, 1);

The SendKeys-method simply sends keystrokes to the active windows.

The Run method is a little more flexible.

$WshShell->Run(Command, [WindowStyle], [WaitOnReturn]);

The WindowStyle can be an integer between 0 through 10, and WaitOnReturn is a boolean value or 1 (TRUE) or 0 (FALSE). FALSE is the default value it means that an immeditate return to script execution contrary to waiting for the process to end is preferable. It also returns an error code of zero while TRUE returns any error code generated by the active application.

Creating Shortcuts

In addition, you can create shortcuts. Either you create a dekstop shortcut or a URL shortcul. The method call CreateShortcut($path_or_url) returns an object reference to a WshShortcut-object. Keep in mind that a dekstop shortcut has tbe extension .lnk and an URL shortcul has the file extension .url. In the latter case, a WshURLShortcut object is returned.

With the WshShortcut-object, one method exists, so it is mainly properties regarding the shortcut that you need to set. The Description-property contains a string describing the shortcut, Fullname returns the full path to the host executable, Hotkey allows for combinations such as "ALT+CTRL+X" as hotkeys for shortcuts on the Windows dekstop or windows startmenu, IconLocation is a property that you set to "Path, index" to provide the Icon location of the shortcut. In addition, use the TargetPath-property to set the path to the executable file pointed to by the shortcut, WindowStyle can be set to either 1, 3, or 7 for the shortcut object, and WorkingDirectory defines the directory in which the shortcut should start. If you are shortcutting a URL, you have only the Fullname and TargetPath properties where the latter one is a URL. All shortcut objects are final when you call the Save method.

Special Folders

The WshShell object can also return a WshSpecialFolders object which contains paths to shell folders such as the desktop, start menu, and personal documents.

<Job Id="SpecialFolder">
<script language=PerlScript>
    $numFolders = $WshShell->SpecialFolders->{Count};
    $title = "PerlScript & WSH Example";
    $style = 1;

    for($i=0; $i<$numFolders; $i++) {
        $ok_or_cancel = $WshShell->Popup(

        exit if ($ok_or_cancel == 2);

Working With the Registry

The WshShell object provides functionality for working with the registry. The three methods for this are: RegRead, RegWrite, and RegDelete. Simply provide either method with a string such as the short form HKCU\ScriptEngine\Val or longer variant HKEY_CURRENT_USER\ScrtipeEngine\Val. Notice that a key is returned if the last character is a backslash, and a value is returned if no backslash is at the end. The RegRead method supports the following data types:

  • REG_SZ

RegWrite requires a few extra parameters:

$WshShell->RegWrite(Name, Value [,Type]);

The name is a fully qualified string such as HKCU\ScriptEngine\Val where the same rules apply for key and value as previously mentioned. The Type-parameter is optional, but if used, it must be one of the following data types:

  • REG_SZ


Expands the requested environment variable from the running process:


In addition, log an event in the NT event log or WSH.log (Windows 9x) file using:

$WshShell->LogEvent(Type, Message [,Target]);

Target is the name of the system on NT, thus only applicable on NT. The Type of event is either

  • 0 (SUCCESS)
  • 1 (ERROR)
  • 2 (WARNING)

This method returns a boolean value indicating success or failure. Another method is Popup, which sends a Windows messagebox up on the screen.

$retval = $WshShell->Popup(Text, [SecondsWait], [Title], [Type]);

The method allows you to define the text to pop up, alternatively seconds to wait before closing window, the title of the window, and lastly the type of buttons available in the window. They can be:

  • 0 (Ok)
  • 1 (Ok and Cancel)
  • 2 (Abort, Retry, and Ignore)
  • 3 (Yes, No, and Cancel)
  • 4 (Yes and No)
  • 5 (Retry and Cancel)

The value that you choose can also be combined with an icon:

  • 16 (Stop Mark)
  • 32 (Question Mark)
  • 48 (Exclamation Mark)
  • 64 (Information Mark)

The return values returned to $retval indicates which button was pressed. The value will be one of the following:

  • 1 (OK)
  • 2 (Cancel)
  • 3 (Abort)
  • 4 (Retry)
  • 5 (Ignore)
  • 6 (Yes)
  • 7 (No)

The WshNetwork Object

The WshNetwork object exposes some network functionality. To begin:

$WshNetwork->AddPrinterConnection($LocalName, $RemoteName[,$UpdateProfile][,$User][,$Password]);

User and password are two parameters with given meaning. Localname and Remotename are the names of the printer resource. Set UpdateProfile to TRUE for storing this mapping in the user profile. Next, AddWindowsPrinterConnection() adds a printer just as you would add one using the control panel. On Windows NT/2000 the only parameter you need to call this method with is the path to the printer while windows 9x requires you to specify the driver to use, and optionally specify which port to which it is connected. In the last event, the syntax is:

$WshNetwork->AddWindowsPrinterConnection($PrinterPath, $DriverName[,$Port])

As easily as adding a printer, you can remove a printer. Simply do

$WshNetwork->RemovePrinterConnection($Name, [$Force], [$UpdateProfile]);

If you set $Force to TRUE (1), it will remove the connection regardless if it is being used, and setting $UpdateProfile to true will remove any user profile mapping.

If you're happy with your printers, you can set one of the printer as your default printer by a quick call:


To return a collection of all your printers, call:

$Printers = $WshNetwork->EnumPrinterConnections();

Then use the Count-property to retrieve the number of items in the $Printers collection object.

When you want to map a drive to a network share, you can use the MapNetworkDrive method.

$WshNetwork->MapNetworkDrive($LocalName, $RemoteName, [$UpdateProfile], [$User], [$Password]);

For example:

$WshNetwork->MapNetworkDrive('C:\', '\\MyComputerServer\\ShareHere);

Remove a network drive using the now familiar syntax

$WshNetwork->RemoveNetworkDrive($Name, [$Force], [$UpdateProfile])

or enumerate the network drives as:

$Drives = $WshNetwork->EnumNetworkDrive();

The three properties of the network object are ComputerName, UserName, and UserDomain.

XML Element Reference

Like Windows Script Components, the Windows Script Host has a set of XML elements that can be deployed. For a basic understanding of how they are used, please refer to the section about Windows Script Components.

The Job Element

The Job element is used to define the beginning and the end of the components. It encapsulates all other tags. Should your WSH file contain more than one job, encapsulate them within a <package> element. When declaring jobs, the ID attribute is optional.


<Job [id=JobID]>

For example:

    <Job id="PrintOutput">
    <Job id="ReadInput">

You can also set a boolean value of true (1) or false (0) for error checking or debugging by using the additional tag

<? job error="true" debug="true" ?>

The Script Element

The script element lets you define the scripting language to use, and then with its closing-tag functions as delimiters for the script code.


<script language="languageName"> code </script>

For example.

<?XML version="1.0"?>
<script language="PerlScriptt">
    sub ReturnValue {
    # Perl code here

The Resource Element

The resource element is a placeholder for strings or numeric data that should be separate from the script commands yet may be used within the script.


<resource id="resourceID"> text or number to represent resource goes here </resource>

You use the getResource(resourceID) to retrieve the contents of the resource specified in the resourceID parameter.

The Reference Element

You can import external type libraries by using the reference element. By importing a type library, you will be able to naturally access the constants that belongs to it, too.


<reference [object="progID" | guid="typelibGUID"] [version="versionNo"] />


Written document copyright (c) 2000 Tobias Martinsson. All rights reserved.



Windows Script Host is copyright (c) 1991-2000 Microsoft Corporation. All Rights Reserved.

 Rough Guide to Windows Script Host