Windows Script Host  

Driving Applications

With WSH you can start applications. The following scripts demonstrate some of these capabilities.

Creating a Local Server Application

Some applications, such as Microsoft Word, expose objects which can be accessed programmatically. The following script uses Word's spell checker.

// JScript.
var Word, Doc, Uncorrected, Corrected;
var wdDialogToolsSpellingAndGrammar = 828;
var wdDoNotSaveChanges = 0;
Uncorrected = "Helllo world!";
Word = new ActiveXObject("Word.Application");
Doc = Word.Documents.Add();
Word.Selection.Text = Uncorrected;
if (Word.Selection.Text.length != 1) 
   Corrected = Word.Selection.Text;
   Corrected = Uncorrected;

' VBScript.

Dim Word, Doc, Uncorrected, Corrected
Const wdDialogToolsSpellingAndGrammar = 828
Const wdDoNotSaveChanges = 0

Uncorrected = "Helllo world!"
Set Word = CreateObject("Word.Application")
Set Doc = Word.Documents.Add
Word.Selection.Text = Uncorrected

If Len(Word.Selection.Text) <> 1 Then 
Corrected = Word.Selection.Text
   Corrected = Uncorrected
End If

Doc.Close wdDoNotSaveChanges

Spawning Programs with Shell.Exec Command

The Shell.Exec command provides additional capability beyond the Shell.Run method. These abilities include:

The following VBScript sample demonstrates how to use standard streams and the Shell.Exec command to search a disk for a file name that matches a regular expression.

First, here's a small script that dumps to StdOut the full path of every file in the current directory and below:

' VBScript.
Option Explicit
Set FSO = CreateObject("Scripting.FileSystemObject")
DoDir FSO.GetFolder(".")
Sub DoDir(Folder)
   On Error Resume Next
   Dim File, SubFolder
   For Each File In Folder.Files
      WScript.StdOut.WriteLine File.Path
   For Each SubFolder in Folder.SubFolders
      DoDir SubFolder
End Sub

Next, this script searches StdIn for a pattern and dumps all lines that match that pattern to StdOut.

' MyGrep.VBS
Option Explicit
Dim RE, Line
If WScript.Arguments.Count = 0 Then WScript.Quit
Set RE = New RegExp
RE.IgnoreCase = True
RE.Pattern = WScript.Arguments(0)
While Not WScript.StdIn.AtEndOfStream
   Line = WScript.StdIn.ReadLine
   If RE.Test(Line) Then WScript.StdOut.WriteLine Line

Together these two scripts do what we want — one lists all files in a directory tree and one finds lines that match a regular expression. Now we write a third program which does two things: it uses the operating system to pipe one program into the other, and it then pipes the result of that to its own StdOut:

// MyWhere.JS
if (WScript.Arguments.Count() == 0)
var Pattern = WScript.Arguments(0);
var Shell = new ActiveXObject("WScript.Shell");
var Pipe = Shell.Exec("%comspec% /c \"cscript //nologo mydir.vbs | cscript //nologo mygrep.vbs " + Pattern + "\"");

See Also

WSH Samples | Exec Method | Run Method