Automating Tasks With Windows Script Host and JavaScript

Windows Script Host (WSH) has been included with Microsoft Windows since Windows 98. Yet I have found that most developers are unaware of the rich scripting possibilities that are present in Windows and are still resorting to DOS batch files for scripting simple tasks, or relying on separate scripting languages such as perl or python. Knowing how to write scripts in JavaScript with Windows Script Host is a convenient way to distribute simple tools to others without requiring them to download and install additional third-party scripting languages.

The WSH component takes a modular approach to providing scripting support for Windows. The application acts as a host for scripting, using an interface that is not specific to the language in which the script is written. To expose a script language to applications, a script engine is implemented. The host and the engine communicate over COM interfaces. This allows applications to expose themselves to scripting without locking the user into a specific scripting language.

WSH ships with engines that support JScript (Microsoft’s implementation of JavaScript) and VBScript. WSH provides a simple host application that allows scripts to be invoked from the command-line and the Windows shell. Two versions of the host application are provided: cscript.exe tailored for executing scripts from a command-line context and wscript.exe tailored for executing scripts from a shell context.

WSH provides interoperability with COM, allowing scripts to consume and provide COM objects. To consume COM objects, the WSH hosts provide a way to instantiate COM objects from their ProgId. To provide COM objects from scripting, the scripts are encapsulated in an XML envelope that provides the necessary metadata that describes the script’s COM interface.

Here is a simple JScript file that outputs an indented listing of files included from a C++ source file:

    1 var g_includeDirs = [
    2     ".",
    3     "C:\\Program Files\\microsoft visual studio 9.0\\vc\\include"
    4 ];
    5 var g_fso = new ActiveXObject("Scripting.FileSystemObject");
    6 var g_indentLevel = 0;
    7 var ForReading = 1;
    8 var g_included = new Object;
    9 
   10 function LocateHeader(name)
   11 {
   12     for (var dir in g_includeDirs)
   13     {
   14         var path = g_includeDirs[dir] + "\\" + name;
   15         if (g_fso.FileExists(path))
   16         {
   17             return path;
   18         }
   19     }
   20     return name;
   21 }
   22 
   23 function ProcessHeader(name)
   24 {
   25     var indent = "";
   26     for (var i = 0; i < g_indentLevel; i++)
   27     {
   28         indent += "  ";
   29     }
   30     WScript.Echo(indent + name);
   31     var path = LocateHeader(name);
   32     if (g_fso.FileExists(path) && !g_included[path])
   33     {
   34         g_included[path] = true;
   35         var header = g_fso.OpenTextFile(path, ForReading)
   36         ++g_indentLevel;
   37         ProcessFile(header);
   38         --g_indentLevel;
   39         header.Close();
   40     }
   41 }
   42 
   43 function ProcessFile(stream)
   44 {
   45     var include = /^\#include <(.*)>/;
   46     while (!stream.AtEndOfStream)
   47     {
   48         var line = stream.ReadLine();
   49         var match = include.exec(line);
   50         if (match)
   51         {
   52             ProcessHeader(match[1]);
   53         }
   54     }
   55 }
   56 
   57 function Main()
   58 {
   59     g_indentLevel = 0;
   60     ProcessFile(WScript.StdIn);
   61 }
   62 
   63 Main();

A couple things you’ll notice about this JScript code:

  • it creates an instance of a COM object whose ProgId is Scripting.FileSystemObject
  • it accesses the standard input with the StdIn property of the global WScript object.
  • it writes to the standard output with the Echo method of the global WScript object.

This particular script assumes that it will be invoked from the console host, cscript.exe. The console host makes the WScript global object available. WSH provides the COM object Scripting.FileSystemObject that allows scripts to manipulate files and directories. It also provides a simple TextStream object for manipulating text files.

WSH lets you combine multiple script files into a single application, allowing you to build libraries of script objects and functions. To combine the scripts together, you create a simple XML file with a wsf extension. For instance, suppose we want to provide the functionality in the above example as a reusable JavaScript object called IncludeAnalyzer. The object implementation would look like this:

    1 function IncludeAnalyzer()
    2 {
    3     this.m_fso = new ActiveXObject("Scripting.FileSystemObject");
    4     this.m_includeDirs = new Object;
    5     this.m_indentLevel = 0;
    6     this.m_included = new Object;
    7 }
    8 
    9 IncludeAnalyzer.prototype.LocateHeader = function(name)
   10 {
   11     for (var dir in this.m_includeDirs)
   12     {
   13         var path = this.m_includeDirs[dir] + "\\" + name;
   14         if (this.m_fso.FileExists(path))
   15         {
   16             return path;
   17         }
   18     }
   19     return name;
   20 }
   21 
   22 IncludeAnalyzer.prototype.ProcessHeader = function(name)
   23 {
   24     var indent = "";
   25     for (var i = 0; i < this.m_indentLevel; i++)
   26     {
   27         indent += "  ";
   28     }
   29     WScript.Echo(indent + name);
   30     var path = this.LocateHeader(name);
   31     if (this.m_fso.FileExists(path) && !this.m_included[path])
   32     {
   33         this.m_included[path] = true;
   34         var header = this.m_fso.OpenTextFile(path, ForReading)
   35         ++this.m_indentLevel;
   36         this.ProcessFile(header);
   37         --this.m_indentLevel;
   38         header.Close();
   39     }
   40 }
   41 
   42 IncludeAnalyzer.prototype.ProcessFile = function(stream)
   43 {
   44     var include = /^\#include <(.*)>/;
   45     while (!stream.AtEndOfStream)
   46     {
   47         var line = stream.ReadLine();
   48         var match = include.exec(line);
   49         if (match)
   50         {
   51             this.ProcessHeader(match[1]);
   52         }
   53     }
   54 }

The code that drives this object now looks like this:

    1 var analyzer = new IncludeAnalyzer;
    2 analyzer.m_includeDirs = [
    3     ".",
    4     "C:\\Program Files\\microsoft visual studio 9.0\\vc\\include"
    5 ];
    6 analyzer.ProcessFile(WScript.StdIn);

However, now we have a problem. If we were reusing this code from a web page, it would be a simple matter of including two <script> blocks to include the library and the code that consumes the library. In WSH, we can do something similar with the mechanism provided by wsf files.

    1 <?XML version="1.0" standalone="yes" ?>
    2 <job id="main">
    3     <?job debug="true" ?>
    4     <script language="JScript" src="IncludeAnalyzer.js"/>
    5     <script language="JScript">
    6         var analyzer = new IncludeAnalyzer;
    7         analyzer.m_includeDirs = [
    8             ".",
    9             "C:\\Program Files\\microsoft visual studio 9.0\\vc\\include"
   10         ];
   11         analyzer.ProcessFile(WScript.StdIn);
   12     </script>
   13 </job>

Now we have a mechanism for creating reusable object and function libraries for scripts without the nuiscance of copy-and-paste code sharing.

You may have noticed that XML processing directive in the above wsf file setting debug to true. You can invoke the full power of the Visual Studio debugger on your JScript and WSF files by invoking the script host with the //x command-line argument:

cscript //x AnalyzeIncludes.wsf

Once the debugger is invoked you can set breakpoints and examine local variables in the watch windows just like any other program. JScript files can always be invoked with the debugger with no additional text in the script file, but WSF files need the job processing directive in order to be invoked in the debugger.

This post just covers the basics of what you can do with Windows Script Host. There is extensive documentation in MSDN covering WSH as well as a syntax reference for JScript, VBScript and the objects provided by the WSH runtime, such as FileSystemObject. There are many pages on the net providing scripting recipes for achieving specific tasks. A good starting point is the Microsoft TechNet Script Center.

You can download the source code shown in this post at the link below.

Download AnalyzeIncludes.zip

3 Responses to “Automating Tasks With Windows Script Host and JavaScript”

  1. Unit Testing JavaScript on Windows « Legalize Adulthood! Says:

    […] take a look at the IncludeAnalyzer object from my post on Windows Script Host and see how we could write unit tests for that object. IncludeAnalyzer collaborates with three […]

    Like

  2. required Says:

    Article needs fixing : the terms Javascript and JScript are interchanged as though there were no distinction.

    Like


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: