Windows Professional / Automating Windows tasks using Windows Scripting Host [ Windows Professional ]
November 1999

Automating Windows tasks using Windows Scripting Host

Do you remember DOS batch files? Batch files are routines that automate certain repetitive tasks. Unfortunately, Windows never offered an equivalent feature; that is, until recently. Windows Scripting Host is a new language-independent scripting host for Windows 9x and NT that lets you build batch applications with Visual Basic Scripting Edition and JScript routines.

In this article, we'll discuss some benefits of Windows Scripting Host, take a closer look at the host, scripting engine, and object collection, and look at the basics of writing and running scripts. We'll also provide a sample script to give you an idea of what's possible with Windows Scripting Host.

Windows Scripting Host's benefits

In the past, the only scripting language supported by Windows was the DOS operating system command language. This was used to create batch files. However, the DOS language has limited features when compared to the VBScript or JScript languages. While DOS scripts are still supported by Windows Scripting Host, today's ActiveX scripting allows users to write more complex script.

Both VBScript and JScript languages allow two-way branching. This means that using a true If/Else statement, a script can make decisions. The script might execute one set of commands if a given condition is true, or another set if the condition is false. In addition, both languages are good at performing math operations, including common trigonometry functions.

Another benefit of Windows Scripting Host is that it allows scripts to be executed directly on the Windows desktop, without embedding those scripts in an HTML document. Scripts are run on the desktop by clicking a script file or entering a command in DOS. Windows Scripting Host is a low-memory host that's perfect for Windows task automation.

The host and script engine

As good as Windows Scripting Host's scripting languages are, they don't allow their scripts to do very much. They can't affect anything outside their own script. The languages don't allow reading or writing disk files, displaying information on the monitor, updating the Registry, or changing the computer in any way.

This is why scripts run under a special program-the host. The host reads the script, interprets the script's language, and calls another program to execute the script's instructions. This program is a language-specific scripting engine. In addition, the host allows scripts to access objects embedded in the host.

Familiar to programmers, an object is a collection of subroutines (methods) and variables (properties) that are available to other programs. These methods and variables are usually related.

Windows Scripting Host's object collection

Windows Scripting Host's collection contains four objects-Wscript, WshShell, WshNetwork, and FileSystemObject. Each object has a variety of methods and properties.

The Wscript object allows scripts to learn information about themselves. In addition, this object allows scripts to launch and control other applications. The key properties and methods for this object are listed in Table A.

Table A: Important properties and methods for the WScript object
Property or method name Function
Path Identifies the directory and path where wscript.exe and cscript.exe reside
Version Identifies the currently installed version of Windows Scripting Host
Echo Displays a text string
GetObject Retrieves an object from a running Windows application, giving the script control of the application
CreateObject Lets scripts access objects stored in Windows applications; these objects allow scripts to control the application
Quit Ends the script

The WshShell object lets scripts install and configure other applications. It also allows scripts to communicate with users, modify the Registry, and locate folders. Some properties and methods for this object are listed in Table B.

Table B: Some WshShell methods and properties
Property or method name Function
Run Launches an application
Popup Lets scripts display text in windows
CreateShortcut Creates shortcuts to files or URLs
SpecialFolders Identifies the full pathname of special folders like the Start menu
RegWrite Creates a new Registry key or writes a new value for an existing key
RegDelete Deletes a Registry key or value

The WshNetwork object is used to create scripts that modify network configurations. This includes tasks like establishing network connections, installing printers, assigning drive letters to network drives, etc. The key properties and methods for WshNetwork are listed in Table C.

Table C: Key properties and methods for the WshNetwork object
Property or method name Function
MapNetworkDrive Maps a user's drive letters to a network drive
EnumNetworkDrives Identifies the network drives connected to the user's computer
AddPrinterConnection Establishes a connection to a network printer
RemovePrinterConnection Removes a network printer connection
SetDefaultPrinter Sets a printer to be the Windows default printer

The last Windows Scripting Host object is FileSystemObject. This object is used to write scripts that perform disk input and output operations. These operations include reading, writing, or deleting disk files and making directories. Some FileSystemObject properties and methods are listed in Table D.

Table D: Properties and methods for the FileSystemObject perform disk operations
Property or method name Function
OpenTextFile Opens a text file so the script can read or write to it
CreateFolder Creates a new folder
DeleteFile Deletes a disk file
CopyFile Copies a disk file
MoveFile Moves a disk file to a different location or renames the file

What you need to get started

The first thing to do is make sure you have Windows Scripting Host. If you're running Windows 98 or Internet Information Server 4.0, you already have it. Windows 95 users can download Windows Scripting Host from the Microsoft Web site at msdn.microsoft.com/scripting.

Microsoft doesn't provide a visual editor for creating Windows Scripting Host scripts. However, Notepad works well for this application.

Creating and running scripts

Compared to some programming experiences, the creation of Windows Scripting Host scripts is relatively simple. In Notepad, you write a script using objects like those in Tables A, B, C, and D. Then simply save your file.

Note: When saving a VBScript file, give the filename a .vbs extension. When saving JScript files, use a .js extension. However, in Notepad's Save dialog box, you should place the filename in quotation marks. If you don't, Notepad will add a .txt extension to the file.

Running scripts is also an easy task. There are a couple different ways to do this. First, you could use the command-based version of Windows Scripting Host from the DOS prompt. This version, C:\WINDOWS\CSCRIPT.EXE, gives you control over how a script executes. This is accomplished by adding parameters to the DOS command.

Host parameters enable or disable Windows Scripting Host options, and are always preceded by two slashes (//). The script name is always the name for script file, and script parameters are passed to the script. Script parameters are always preceded by one slash (/). Table E lists host parameters supported by CSCRIPT.EXE.

Table E: Host parameters support by CSCRIPT.EXE
Parameter Description
//B Sets a time out in seconds, allowing a maximum time the script can run
//I Sets the interactive mode, which re-enables script output messages
//logo Displays an execution banner at execution time
//nologo Prevents the display of an execution banner at execution time
//H:Cscript or Wscript Makes CSCRIPT.EXE or WSCRIPT.EXE the default application for running scripts
//S Saves the current command line options for the current user
//? Shows the command usage, which is the same as execution with no parameters

If you don't want to specify parameters when you run a script, use the Windows-based version of Windows Scripting Host. There are three ways to run scripts with this version.

One way to run scripts with this version is to simply double-click on files and icons in My Computer, Windows Explorer, and Find windows. Another method is to select Run from the Start menu, then type the full name of script you want to run in the Open text box. The final option is to run WSCRIPT.EXE from the Run command, specifying the script name and any optional parameters.

Sample script

Let's look at a sample script written in VBScript. The particular example in Listing A was provided by Microsoft, and can be downloaded from their Web site (along with several others) at msdn.microsoft.com/scripting/. You can also download the script code from our ftp site at ftp.zdjournals.com/w9p.

This script creates a shortcut to Notepad on your desktop. It should be noted that the scope of this article won't teach you VB or Java programming. However, this example will give you an idea of what Windows Scripting Host can accomplish with some basic programming knowledge.

Listing A: Shortcut.vbs

' This sample demonstrates how to use the WSHShell object
' to create a shortcut on the desktop.

L_Welcome_MsgBox_Message_Text   = _
    "This script will create a shortcut to Notepad on your desktop."
L_Welcome_MsgBox_Title_Text     = "Windows Scripting Host Sample"
Call Welcome()

' ***************************************************************
' *
' * Shortcut related methods.
' *

Dim WSHShell
Set WSHShell = WScript.CreateObject("WScript.Shell")

Dim MyShortcut, MyDesktop, DesktopPath

' Read desktop path using WshSpecialFolders object
DesktopPath = WSHShell.SpecialFolders("Desktop")

' Create a shortcut object on the desktop
Set MyShortcut = WSHShell.CreateShortcut(DesktopPath & _
    "\Shortcut to notepad.lnk")

' Set shortcut object properties and save it
MyShortcut.TargetPath = WSHShell.ExpandEnvironmentStrings _
    ("%windir%\notepad.exe")
MyShortcut.WorkingDirectory = WSHShell.ExpandEnvironmentStrings _
    ("%windir%")
MyShortcut.WindowStyle = 4
MyShortcut.IconLocation = WSHShell.ExpandEnvironmentStrings _
    ("%windir%\notepad.exe, 0")
MyShortcut.Save

WScript.Echo "A shortcut to Notepad now exists on your Desktop."

' ****************************************************************
' *
' * Welcome
' *
Sub Welcome()
    Dim intDoIt

    intDoIt =  MsgBox(L_Welcome_MsgBox_Message_Text, _
        vbOKCancel + vbInformation, _
        L_Welcome_MsgBox_Title_Text )
    If intDoIt = vbCancel Then
       ;WScript.Quit
    End If
End Sub

Conclusion

Windows Scripting Host is a strong successor to the batch files of the past. In addition to being supported by all Win32 programs, a growing number of outside vendors support the product and provide additional scripting engines, hosts, etc. With a little programming skill, you can write your own scripts to automate Windows functions. Even if you don't feel comfortable writing your own scripts, there are plenty available for download from the Web. Trust me, Windows Scripting Host scripts will make your life easier!

Copyright © 1999, ZD Inc. All rights reserved. ZD Journals and the ZD Journals logo are trademarks of ZD Inc. Reproduction in whole or in part in any form or medium without express written permission of ZD Inc. is prohibited. All other product names and logos are trademarks or registered trademarks of their respective owners.