Windows 7 : Command-Line and Automation Tools – Windows Script Host

In the last decade or so, Microsoft has worked diligently to provide ways for programmers to gain access to the internal functions of commercial applications such as Word and Excel and of Windows itself. The approach is based on a technology called the Component Object Model, or COM, which lets a properly designed program share its data and functional capabilities with other programs—any other programs, written in any other programming language. If you’ve ever written macros for Word or Excel, you’ve worked with scripting and COM. One product of these efforts is Windows Script Host, or WSH, which provides a fast and easy way to write your own management and utility programs. Scripts have an advantage over batch files in that they can perform complex calculations and can manipulate text information in powerful ways because you write them in a full-featured programming language.

Scripts can massage, digest, and manipulate text files and data, view and change Windows settings, and take advantage of Windows services through COM objects provided as a standard part of Windows. In addition, if you have COM-enabled applications such as WordPerfect, Microsoft Word, or Excel installed, scripts can even enlist these applications to present information in tidy, formatted documents and charts.

Windows comes with support for two different scripting languages:

  • VBScript— Nearly identical to the Visual Basic for Applications (VBA) macro language used in Word and Excel.

  • JScript— Microsoft’s version of the JavaScript language, which is widely used to make web pages interactive. (JavaScript, by the way, is not the same thing as Java. Java is another programming language altogether.)

In addition, you can download and install scripting support for other languages. If you have a UNIX or Linux background, for example, you might want to use the Perl, Python, or TCL scripting languages. You can get free WSH-compatible versions of these languages at www.activestate.com.

If you are already versed in one of the scripting languages I’ve mentioned, by all means, use it. If you don’t already know a scripting language, VBScript is probably the best one to start with because you can also use it to write macros for Microsoft’s desktop applications.

Creating Scripts

Just like batch files, scripts are stored as plain text files, which you can edit with Notepad or any other text file editor. To create a script file, choose a descriptive name, something like WorkSummaryReport perhaps, and add the extension that corresponds to the language you’ll be using. A script written in the VBScript language must have its filename end with .vbs.

As an example, I’ll write a script that I’ll call hello.vbs. If you want to try it yourself, the steps are

1.
Open a Command Prompt window by clicking Start, All Programs, Accessories, Command Prompt.

2.
The Command Prompt window opens on the default directory \users\your_user_name. If you want to create the script in another folder, you will need to type in a cd command to change directories. (You might want to put your scripts into folder C:\scripts, and add that folder to the PATH.) But for the purposes of this example, we’ll skip that and use the default directory.

3.
Type the command notepad hello.vbs. When Notepad asks whether you want to create a new file, click Yes.

4.
Type in the text

wscript.echo "Hello, this message comes from a script"


5.
Save the script by selecting File, Save. You can leave the Notepad window open, or close it with File, Exit.

6.
Bring the Command Prompt window to the foreground.

7.
Type hello and press Enter.

If everything works, you see the dialog box shown in Figure 1. Click OK to close the dialog box.

Figure 1. The sample script displays a simple text message.

WSH can display its results in a window, as you just saw, or it can display results in the console window, as do most command-line programs. As you saw in the previous sample, the default is to display information in a window because the default interpreter for scripts is wscript. It’s usually best to change the default so that the default mode is the text-based console output method. To do this, type this command:

cscript //H:cscript //nologo //s
 

(Notice that the slashes are doubled-up in this command.) Now, type the command hello again. This time the script’s output should display within the Command Prompt window.

Some Sample Scripts

Disk and Network Management

WSH comes with tools to examine and modify drives, folders, and files. Here is an example of a VBScript script that performs a reasonably useful task:

set fso = CreateObject("Scripting.FileSystemObject")
set drivelist = fso.Drives
for each drv in drivelist
    if drv.IsReady then
        wscript.echo "Drive", drv.DriveLetter, "has", drv.FreeSpace, "bytes free"
    end if
next

					  

It displays the amount of free space on each of your computer’s drives. Type this script into a file named freespace.vbs in your batch file directory, and then type the command-line command freespace. On my computer this prints the following:

Drive C: has 15866540032 bytes free
Drive D: has 27937067008 bytes free
Drive F: has 335872000 bytes free
Drive H: has 460791808 bytes free

WSH can also work with networking features. The following VBScript script displays your computer’s current network drive mappings:

set wshNetwork = CreateObject("WScript.Network") ' create the helper object

set maps = wshNetwork.EnumNetworkDrives   ' collection describes mapped drives
for i = 0 to maps.Length-2 step 2         ' step through collection by twos
    wscript.echo "Drive", maps.item(i), "is mapped to", maps.item(i+1)
next

					  
Windows Management Instrumentation

Windows Management Instrumentation (WMI) is a system service that provides access to virtually every aspect of a Windows computer system, from the hardware components up to the highest-level system services. For some components, WMI provides information only. Other components can be changed, and thus, as its name implies, WMI can be used to manage the system. You can use WMI to start and stop system services, monitor and stop applications, create drive mappings, share folders, and, with the appropriate updated WMI drivers installed, even manage system services such as Internet Information Services, Microsoft Exchange, and the Domain Name Service on Windows Server.

The following script lists the status of each system service installed on your computer. This script file can be named showservices.vbs. (The underscore at the end of some of the lines are part of the script.)

set services = GetObject"winmgmts:{impersonationlevel=impersonate," &_
        "authenticationlevel=pkt}!" &_
        "/root/CIMV2:Win32_Service")    ' get services WMI info

for each svc in services.Instances_     ' display information for each service
    wscript.echo svc.name, "State:", svc.State, "Startup:", svc.StartMode
next

					  

On my computer, the first few lines of output from this script look like this:

AeLookupSvc State: Stopped Startup: Manual
ALG State: Stopped Startup: Manual
AppIDSvc State: Stopped Startup: Manual
Appinfo State: Running Startup: Manual
AppMgmt State: Stopped Startup: Manual

Remember, too, that as command-line programs, you can redirect the output of these scripts into a file. The command

showservices >listing.txt

puts the service list into file listing.txt, just as if showservices was a native Windows executable program.