May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Windows Scripting Host (WSH)



Recommended Links VBA Frontpage Scripts

Scripting with Windows PowerShell

Wsh changed the playing field for Windows and moved it above Unixes which had a sobering  impact on Linux enthusiasts, who always keen to criticize the "mouse" productivity of Windows environment. You can use JavaScript shell in Windows applications and there are many books to teach those great productivity tools that come with the Microsoft OS. With WSH you can do really interesting things including sending keystokes to programs.

Windows Script Host (WSH) 5.6 is the new version of the Windows scripting environment that Microsoft bundles with Windows XP. This new environment is also available for Windows 2000, Windows NT 4.0, and Windows Me. You can download the executable from Microsoft's scripting Web site at . But before you begin experimenting with the new version, you'll benefit from an overview of the environment's new features.

First Impressions

The first thing you're likely to notice about WSH 5.6 is the unusual version number. The preceding version of WSH was 2.0; why did Microsoft jump to WSH 5.6? Some people guessed that Microsoft wanted WSH to match XP's version number; however, XP is version 5.1 of Windows. Microsoft made the new WSH version number correspond to the version number of Windows Script. WS is the scripting infrastructure that consists of WSH, VBScript, JScript, Windows Script Components (WSC), and Windows Script Runtime.

An interesting feature of Windows 2000 Reskit is that it contains 83 VBScript programs that perform various system related tasks:

11/04/1999 10:32a 23,784 bootconfig.vbs
11/04/1999 10:32a 21,438 bus.vbs
11/04/1999 10:32a 22,527 cacheinfo.vbs
11/04/1999 10:32a 23,224 cdromdrives.vbs
11/04/1999 10:32a 24,730 checkbios.vbs
11/04/1999 10:49a 60,515 chkusers.vbs
11/04/1999 10:49a 19,486 ClassifyMembers.vbs
11/04/1999 10:48a 17,803 clean.vbs
11/04/1999 10:48a 81,676 clone.vbs
11/04/1999 10:32a 27,844 codecfile.vbs
11/04/1999 10:32a 22,020 compsys.vbs
11/04/1999 10:48a 7,462 conall.vbs
11/04/1999 10:49a 30,278 createusers.vbs
11/04/1999 10:48a 6,850 defprn.vbs
11/04/1999 10:32a 21,894 desktop.vbs
11/04/1999 10:32a 45,848 device.vbs
11/04/1999 10:32a 17,031 devicemem.vbs
11/04/1999 10:32a 23,137 diskpartition.vbs
11/04/1999 10:32a 21,355 dmachan.vbs
11/04/1999 10:32a 24,078 drives.vbs
11/04/1999 10:48a 16,962 drvmgr.vbs
11/04/1999 10:32a 23,805 enabledhcp.vbs
11/04/1999 10:31a 24,845 enumclasses.vbs
11/04/1999 10:31a 25,480 enuminstances.vbs
11/04/1999 10:32a 22,367 enumnamespaces.vbs
11/04/1999 10:32a 22,114 eventlogmon.vbs
11/04/1999 10:32a 25,577 exec.vbs
11/04/1999 10:32a 37,449 fileman.vbs
11/04/1999 10:48a 15,299 forms.vbs
11/04/1999 10:32a 22,599 group.vbs
11/04/1999 10:49a 16,832 GroupDescription.vbs
11/04/1999 10:32a 21,332 irqres.vbs
11/04/1999 10:32a 22,124 keyboard.vbs
11/04/1999 10:32a 19,956 ldordergrp.vbs
11/04/1999 10:32a 22,980 listadapters.vbs
11/04/1999 10:49a 16,244 ListDCs.vbs
11/04/1999 10:32a 22,319 listdisplayconfig.vbs
11/04/1999 10:49a 17,904 ListDomains.vbs
11/04/1999 10:32a 22,643 listfreespace.vbs
11/04/1999 10:49a 17,880 ListMembers.vbs
11/04/1999 10:32a 22,569 listos.vbs
11/04/1999 10:32a 22,920 listprinters.vbs
11/04/1999 10:49a 18,139 listproperties.vbs
11/04/1999 10:32a 22,559 listspace.vbs
11/04/1999 10:32a 23,559 logmeminfo.vbs
11/04/1999 10:32a 22,969 lstdpconinfo.vbs
11/04/1999 10:49a 42,475 ModifyLDAP.vbs
11/04/1999 10:49a 33,818 ModifyUsers.vbs
11/04/1999 10:32a 22,330 motherboard.vbs
11/04/1999 10:32a 22,014 netconnections.vbs
11/04/1999 10:32a 23,713 networkprotocol.vbs
11/04/1999 10:32a 29,820 osreconfig.vbs
11/04/1999 10:32a 31,994 pagefile.vbs
11/04/1999 10:32a 21,561 parallelport.vbs
11/04/1999 10:48a 9,940 persist.vbs
11/04/1999 10:32a 22,171 pointdev.vbs
11/04/1999 10:48a 15,814 portconv.vbs
11/04/1999 10:48a 19,651 portmgr.vbs
11/04/1999 10:48a 20,909 prncfg.vbs
11/04/1999 10:48a 8,881 prnctrl.vbs
11/04/1999 10:48a 13,159 prndata.vbs
11/04/1999 10:48a 19,429 prnmgr.vbs
11/04/1999 10:32a 22,112 processor.vbs
11/04/1999 10:32a 21,879 programgroups.vbs
11/04/1999 10:32a 21,726 protocolbinding.vbs
11/04/1999 10:32a 28,472 ps.vbs
11/04/1999 10:32a 26,590 pstop.vbs
11/04/1999 10:32a 40,236 query.vbs
11/04/1999 10:32a 26,829 regconfig.vbs
11/04/1999 10:32a 35,533 restart.vbs
11/04/1999 10:49a 26,342 SchemaDiff.vbs
11/04/1999 10:32a 21,603 scsicontroller.vbs
11/04/1999 10:32a 21,746 serialport.vbs
11/04/1999 10:32a 45,273 service.vbs
11/04/1999 10:32a 37,817 share.vbs
11/04/1999 10:32a 21,539 sounddevice.vbs
11/04/1999 10:32a 21,920 startup.vbs
11/18/1999 02:07p 17,446 subnet_op.vbs
11/04/1999 10:32a 21,226 systemaccount.vbs
11/04/1999 10:32a 23,447 tapedrive.vbs
11/04/1999 10:32a 22,141 thread.vbs
11/04/1999 10:32a 25,729 useraccount.vbs
11/04/1999 10:49a 17,799 Usergroup.vbs

Among them you can notice few reimplementation of classic Unix utilities, like ps.vba, pstop.vbs, exec.vba. Many perform useful Windows  functions like listos.vbs (Lists information about version of Windows  installed on a particular machine).

Top Visited
Past week
Past month


Old News ;-)

[Feb 17, 2006] Monad - Microsoft Vista Shell Scripting Language Digital Inspiration Software Reviews, Technology News, Web Guide, Downloads, Productivity Tips

Luckily, you don't need Windows Vista to start using Monad. Just Download and install Monad shell with the .Net Framework 2.0 from the Microsoft Download Center and start scripting. Monad is not quite a superset of the XP cmd shell. You can execute traditional commands as before, but the built-in commands all behave different.

Monad MSH shell will also add powerful text manipulation capabilities to Vista which were earlier only possible with sed or awk programs that are also ported to Windows. Tools like MKS Toolkit and Cygwin are popular among Unix Software Developers who are moving to Windows since they provide bash, ksh style scripting on Windows. Monad could target that market as well.

Download Windows Monad Shell Documentation | Msh Language Quick Start | Scripting with the Windows Monad Shell | Monad Shell | Download Windows Monad Shell | Microsoft has big plans for the trusty old C:\ prompt | Monad Technology Blog

[Jul 18, 2005] Easy Scripting

by Mitch Tulloch

Writing scripts for Windows isn't like writing batch scripts for MS-DOS; the scripting capabilities of the latest version of Windows (XP/2003) are far more powerful than the batch scripting language but also far more complex. Microsoft has an excellent site on TechNet, the Script Center, that has lots of tutorials, articles, and resources to help you learn how to write Windows scripts. But the actual process of writing scripts hasn't really changed from the way we used to write batch files for DOS--it's still basically all about opening up Notepad and doing a bunch of typing, carefully. Isn't there an easier way to write scripts?

Well, the first thing you can do is see if someone has already written a script that can do what you're looking for. The Script Center Script Repository has just that--hundreds of sample scripts you can use as is or customize as needed. Or you can Google and see what other sites have collections of Windows scripts, because there are many of them around. One of my favorites is the VB Scripting Downloads section of, a site run by Rod Trent, a friend of mine. Most of the scripts here are for use in SMS/MOM environments, but you can find lots of other useful stuff too. If you know of other good Windows script repositories, let me know in the feedback section below and I'll share it with others.

If you can't find an existing script that can do what you want, try posting to one of the scripting newsgroups on These include:

You can access these groups either in a newsreader using news:// or using a web-based interface on the Newsgroups page of the Microsoft Communities web site. Whichever method you choose, post your scripting need in the right group and you're likely to find someone who will write it for you just for the sheer exhilaration. (Some people get exhilarated by the strangest things; I like blue skies and red sunsets myself.) Or go to one of the many other popular online IT communities around: the discussion forums, Experts Exchange, and others. Again, I'd be interested in hearing which online forums you find most useful for getting help in writing scripts.

If you lean toward the power end of things, try searching the Microsoft Download Center for tools to help you write scripts. Goodies you'll find there include HTA Helpomatic, a tool that can be used to create HTML Applications (HTAs) for your scripts so they can have a graphical user interface that includes check boxes, radio buttons, list boxes, and other controls. You can use Helpomatic to build a front end for your script to make it easier to use, and you can even run different scripts by clicking on different buttons on a web page. Then there's Scriptomatic 2.0, a newly revised tool that helps you easily write Windows Management Instrumentation (WMI) scripts even if you're a novice at understanding how WMI works. WMI is a powerful interface in Windows that lets you view and change configuration settings for almost any component of a Windows system or network. You can also find the TechNet Script Center sample scripts on the Download Center in one easy-to-download package. This is really convenient and saves time browsing through pages of scripts in the Script Center and copying scripts one at a time and saving them. There's even a Do-It-Yourself Script Center Kit that lets you build your own version of the TechNet Script Center, either as a web site or a Windows Help (.chm) file.

Finally, consider all the books out there on Windows scripting. There are a number of good ones, especially for learning how to script, but if you're just looking for some quick and dirty scripts to use and maybe customize a bit, pick up a copy of Windows Server Hacks (there he is, shamelessly promoting his book again!), which contains dozens and dozens of scripts developed by the community and other "geeks like us."

Happy scripting!

Mitch Tulloch is the author of Windows 2000 Administration in a Nutshell, Windows Server 2003 in a Nutshell, and Windows Server Hacks.

[Jun 10, 2005] Automate Tasks with Scriptomatic

Hard-working programmers solve problems, but good programmers solve their problems once by writing tools to automate repetitive tasks.
When I was in college, I had the good fortune to take several computer science classes from one of Georgia Tech's legends, a man named gus Baird (his real name was Augustus, and he insisted that the g in gus be lower case). gus was a terrific instructor. Among the basic principles he taught was a simple one: Hard-working programmers solve problems, but good programmers solve their problems once by writing tools to automate repetitive tasks.

The release of the new version of Scriptomatic from the Microsoft Scripting Guys (see ) reminded me of gus's maxim. Scriptomatic automates the process of writing several different kinds of WMI scripts, which has two benefits. For new scripters, it drastically lowers the difficulty of using WMI; for experienced scripters, it provides a simple way to crank out new scripts from a known set of basic scripts. After you download the Scriptomatic 2.0 from and install it, you'll find that you've suddenly gained the ability to create about multiple types of scripts. The original

Scriptomatic could produce only VBScript code, but the new version can write scripts in the popular Perl and Python scripting languages, as well as in JavaScript. Better yet, you can easily target a single script at multiple computers, giving you an easy way to write one script that automatically gathers data from all your Exchange servers. Best of all, you can choose the output format for the script's data. The default dumps data on the command line, but you can also output plain text, HTML, Microsoft Office Excel, or XML format data to a file. How easy is Scriptomatic to use? Check out the script I created (see below), which displays all the properties of the DSAccess objects exposed by

Support - IIM - Reliable Web Browser Automation - Web Testing - Scripting

Slashdot Wicked Cool Shell Scripts

Re:What about us Windows users?! (Score:4, Interesting)
by Osty (16825) on Wednesday March 10, @04:27PM (#8525236)
Exactly. What makes shell scripts so much better on Unix isn't really the shell, it's the flexibility of the programs that come with a Unix.

That's true, but the fallacy is that you're assuming Windows should be scripted in the same fashion as *nix. That's simply not the case. Batch/Command scripting is nice for small bits, and can actually be fairly powerful in an obtuse sort of way, but the real power in automating Windows comes by using the Windows Scripting Host, JScript or VBScript, and all of the ActiveX/COM interfaces into the functionality of the OS and other applications. A classic example is iterating through users. In *nix, you write a shell script to parse through /etc/passwd. In Windows, you write a jscript to instantiate the objects that deal with Active Directory, and iterate through user objects (each of which you can perform actions upon, wherein *nix you'd have to invoke other applications). One approach is not necessarily "better" than the other, but you can't assume that your *nix administration experience will directly translate into Windows administration. You'd laugh if a Windows admin felt the reverse was true. What really gets me is when people complain about Windows not being automation-friendly because they're used to *nix scripting. Yes, you cannot pipe notepad.exe into winword.exe, for example, but Word has a very rich automation interface that you can hook into and use from a simple JScript.

Take the DELETE command. It has trouble deleting multiple files at a time. It can't delete directories. Then look at Unix rm. It's easy to see why batch files are a joke.

What? Try running "help del" from a cmd.exe window some time. Also, look at "help rd". If you want to remove a directory tree, you use the "remove directory" command. "del" deletes files. "rd" deletes directories (and can delete files within directories if you tell it to).

The shell itself is definitely more flexible overall, though. Definitely more scriptable. The Bourne way of doing conditions, loops, pipes and whatnot are definitely more intuitive, more flexible, and carry less baggage than or cmd.exe.

Consider cmd.exe to be the functional equivalent of csh. It's a decent interactive shell, and has some good functionality (especially later versions of cmd.exe in win2k and xp), but you'd have to be nuts to do any extensive scripting with it. Just as you'd pull out bash or perl to do more complex tasks in *nix rather than using csh, you should use WSH in Windows for more complicated tasks.

Re:Is that a recipe for bloat? (Score:5, Informative)
by plover (150551) * on Wednesday March 10, @06:38PM (#8526682)
( | Last Journal: Monday December 22, @11:28AM)
While I agree with you that piping the output of one program into another to stack utility upon utility is a great feature of [c|k|ba]sh, I don't think you weren't paying attention to the parent post.

The trick with Windows is that you can do many of these same things, but this power comes from doing it in WSH or VB (or C/C++ or an ASP or whatever language you're comfortable with. I've even done it in Perl.) You use the COM interfaces of the shell object to enumerate through directory trees and files. You can stream each of those files into the COM interface of another program that accepts streams. You can search, you can pipe stuff all over, and you're not limited to a single instance of stdin, stdout and/or stderr.

It's not unlike shell scripting, it's just a different language. Each application is able to expose whatever it feels is most important in whatever fashion it thinks is best. DevStudio, for example, lets the scripting host user get to the workspace, the project, and any of the tools.

The biggest problem I have with it is that stdio is not "guaranteed" to be supported by every application under Windows. stdio is the glue that binds all the UNIX utilities together. That's the beauty of stdio -- as the sole mechanism for I/O for most tools, it became the defacto application interaction interface. Windows doesn't have that: most Windows apps don't offer any automated IO at all. And some of the ones that do seem to have interfaces pasted on after the fact. But the ones that do expose properties and methods via COM are easy to access, and easy to control from anywhere. And using the interfaces tends to remove the ambiguities: in UNIX if you're using 'cut' to parse a phone list but the name field sometimes contains commas, you end up hacking around solutions to make them work. A COM-based solution would provide an interface containing a Name field.

Windows is not alone in this limiation, either. UNIX suffers from a similar problem: how do you meaningfully pipe data to and from an X window, or even to a curses app? Is it consistent between apps? Most apps I am familiar with that offer such features in their applications had to have code added to actively support a meaningful commandline interface to their programs through the use of dozens of command line switches. Without this sort of code, using stdio to parse the output of a curses-based application becomes a tedium of screen scraping.

Don't get me wrong: I have a bevy of UNIX-like command line utilities for Windows, I use Cygwin and bash when I need to (although the file system mapping is worse than I could have imagined), and I will fire up a CMD script long before I think to write it as a VB or C++ program. I'm far more comfortable with the sh-style tools -- I grew up with them.

I'm not saying stdio is better or worse than using the COM interfaces of Windows; I'm just saying it's "different." And you certainly shouldn't be reinventing the wheel to script up utilities in Windows.

LAZARUS AT LARGE Sensitive data can get in the wrong hands David Lazarus

November 30, 2003

Wells Fargo says there's no evidence that sensitive information on thousands of customers was misused, now that authorities have recovered a computer stolen from a Concord business consultant working for the bank.

That remains to be seen. The computer is today in the hands of Secret Service technicians, who are trying to determine whether any of the names, addresses or Social Security numbers stored on its hard drive were accessed or downloaded.

In any case, the FBI estimates that stolen computers are responsible for more than half of all thefts of confidential corporate data. The bureau, working with San Francisco's Computer Security Institute, says cyber-crimes caused more than $201 million in losses to 530 companies surveyed last year.

"You never hear about people getting their hardware back," said Robert Richardson, editorial director of the Computer Security Institute in San Francisco. "But recovering the hardware is usually pretty irrelevant. By the time you get it, whoever wanted something from it would already have it."

In Wells' case, the theft of the consultant's computer took place in the early hours of Saturday, Nov. 1, according to police. Two weeks passed before Wells notified customers of the break-in -- as required by law -- and then another week went by before the company said it was posting a $100,000 reward for info leading to the arrest of the perpetrator.

That reward is apparently going nowhere. Investigators say they tracked down the suspect, identified as 38-year-old Edward Krastof, on their own. Krastof will be arraigned Tuesday on felony charges of burglary, possession of stolen property and identity theft.

Not all such cases, though, are solved so quickly or easily. Just one day before Wells' data were stolen, thieves broke into the Roseville branch office of brokerage Merrill Lynch near Sacramento. They made off with about a dozen computers.

On Nov. 3, Merrill sent its legally required notification to clients. "We believe there is little, if any, confidential client information on the stolen computers that can be accessed by the perpetrators without knowing confidential passwords," it said.

"The reaction from clients, all things considered, was positive," said Bill Halldin, a spokesman for the brokerage. "They were glad we informed them about what happened."

Maybe the clients' upbeat response was due in part to how the letter was phrased. What it didn't say was that beyond the password protection, the names,

addresses and Social Security numbers of at least some of Merrill's thousands of clients in the region could be found on the hard drives of the stolen gear.

"We told people what we knew at the time," Halldin explained. "We now know that, in some instances, there was information on some computers and, in other instances, we believe there's information on some computers.

"But what we said before is still accurate," he stressed. "You'd still have to know the passwords to get the information."

Security experts say this is hardly reassuring.

"To anyone who knows what they're going after, passwords mean nothing more than a speed bump," said Benjamin Jun, vice president of Cryptography Research, a San Francisco computer-security consulting firm.

"Password protection is generally only used to keep honest people honest, " he said. "In many cases, getting around password protection is as easy as removing the hard drive and plugging it into another computer."

Sarah Groark, chief executive of Procinct Security, another San Francisco consulting firm, agreed that passwords pose little challenge to anyone who knows what he's doing.

"You can just download tools that will open most passwords," she said. "Passwords will not keep out a determined cyber-attacker."

Merrill's Halldin later elaborated on the situation. He observed that the information on the stolen computers is even more secure than previously thought.

"In some cases, we're talking multiple passwords," Halldin said.

Lt. Mark Toupin of the Roseville Police Department said investigators have no leads as to the whereabouts of Merrill's computers. "We have nothing pointing us toward a suspect at this point," he said.

The thefts from Merrill Lynch and Wells Fargo's consultant underline the challenge companies face in trying to keep a lid on the reams of information collected from customers.

Such data can slip out via a contractor (or subcontractor) in the United States or abroad. It can also get away through something as mundane as an office burglary.

"There's too much data that's not being properly accounted for," said Richardson at the Computer Security Institute. "We're just not holding responsible parties responsible."

He cites the growing number of identity thefts nationwide as evidence of this trend. Federal authorities estimate that in the last year alone, nearly 10 million Americans were victims of identity theft.

Yet few if any companies are held accountable for actions that may have placed consumers' information in peril -- such as outsourcing -- or for not adopting more stringent measures to safeguard such data.

"At some point, someone in the chain isn't a responsible steward of information," Richardson said. "But the people who end up paying for it are the ones stuck with cleaning the mess, usually the consumers."

That's a lesson customers of Wells Fargo and Merrill Lynch would rather not learn the hard way.

David Lazarus' column appears Wednesdays, Fridays and Sundays. He also can be seen regularly on KTVU's "Mornings on 2." Send tips or feedback to [email protected].

What's New In WSH 5.6



Script (.WS/.WSF)

Description - XML-based

Windows 2000: Script extension must be .ws
Windows NT: Script extension must be .wsf
An example of how to use PerlScript within Windows Script. You can see the script in Perl and in PerlScript in Windows Script File format. One nice advantage to running PerlScript instead of Perl is PerlScript runs in Windows, where as Perl runs in a command window - it just looks cleaner in Windows.
ActiveState ActivePerl 5.6 and Windows Scripting Host 5.1 or greater are required to execute a PerlScript WSF file on NT/W2K.
If you are using Internet Explorer, the link to will probably come up blank. Try View Source. An XML-port of the VBS script SynchTime.vbs below.
ServerInfo.wsf Searches all the servers in the domain, or matches server names to a regular expression, and reports on the version numbers of certain system components. Currently (version 1.2), the following components are checked: Service Pack, Internet Explorer, MDAC and pcAnywhere. There is also an option to print the output in comma-delimited format, and the script also checks for the engine that executes it (WScript.exe or CScript.exe) and formats the output accordingly (in a window or to the command line, respectively).
WhichDom.wsf Displays the domain to which a computer or a list of computers belong. It will also inform you if a computer cannot be found or if it is not a member of a domain.
ListAdmins.wsf Displays the membership list of the local Administrators group for all machines in a domain. You can also specify a regular expression to pattern match a select group of machines.
ListPerms.wsf Enumerates all the non-administrative shares on computers, and if the p roper switch is set fixes some share problems. Good example of PerlScript an XML WSH script.
UserAudit.wsf UserAudit queries the domain and displays all users that have the Password Never Expires option checked in User Manager. For most accounts, that should be considered a security violation, so it's a good thing to check on.
Computer Account Age Reporter and Remover If you've worked on a Microsoft networks, you've probably seen some long, long lists of grayed-out computer accounts in Server Manager. This script enumerates all computer accounts (or all regular expression matches) in a domain and displays the number of days since the last update of the computer account password. Unless default security is changed, computer account passwords are automatically updated every seven days or the next time the computer connects to the domain after the seventh day. With this script, you can display a list of all computers that have not connected in n days, and you can have the script automatically delete those accounts from the domain!

Microsoft Windows 2000 Scripting Guide - Sending Keystrokes to a Program

Sending Keystrokes to a Program

Microsoft® Windows® 2000 Scripting Guide

By providing scripts with access to most COM objects, WSH enables you to automate applications that have a COM-based object model. Unfortunately, some applications, especially older ones, do not have a COM-based object model. To automate these applications, WSH provides a way to send keystrokes to these applications.

When you use the WshShell SendKeys method to send keystrokes to an application, your script mimics a human typing on the keyboard. To send a single keyboard character, you pass SendKeys the character itself as a string argument. For example, "x" to send the letter x. To send a space, send the string " ". This is exactly what a user would do if he or she was working with the application: to type the letter x, the user would simply press the x key on the keyboard.

When you use the SendKeys method, special keys that do not have a direct text representation (for example, CTRL or ALT) are represented by special characters. Table 3.16 lists these SendKeys representations for commonly used keys.

Table 3.16 SendKeys Representations of Common Keys

Key SendKeys Representation














{ENTER} or ~



































All function keys, like F1, are represented by the button name contained within braces for example, {F1} for the F1 button and {F2} for the F2 button.

For example, the following script starts Notepad and then types the sentence, "This is a test."

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "Notepad.exe"
Do Until Success = True
    Success = objShell.AppActivate("Notepad")
    Wscript.Sleep 1000
objShell.SendKeys "This is a test."

When the script runs, Notepad will open, and the sample sentence will be typed in, as shown in Figure 3.12.

Figure 3.12 Controlling Notepad by Using SendKeys


See full-sized image.


You can send repeated keystrokes by using the SendKeys method. For example, to send the letter a ten times, you send the string "{a 10}". You must include a space between the keystroke and the number. SendKeys allows you to send only repeated single keystrokes. You cannot send multiple characters using repeated keystrokes; for example, this command will fail: {dog 10}.

You should be aware that sending keystrokes to an application is not the optimal method for automating a procedure. If you have an application in your enterprise that you need to automate and it has no COM-based object model, you might consider this technique. However, you should first examine whether other methods exist for automating that particular application.

Although SendKeys can be used effectively, there are several potential problems with this approach:

The script might have difficulty determining which window to send the keystrokes to.
Because the application runs in GUI mode, a user might close the application prematurely. Unfortunately, this will not terminate the script, and the script could end up sending keystrokes to the wrong application.
The script might have difficulty synchronizing with the application.

This timing issue is especially troublesome, simply because scripts tend to run much faster than GUI applications. For example, this simple script, which starts Calculator and then tries to type the number 2 into the application, is coded correctly but will likely fail when run (Calculator will start, but the number 2 will not be entered):

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "Calc.exe"
objShell.AppActivate "Calculator"
objShell.SendKeys "2"

The script fails not because of a syntax issue but because of a timing issue. As quickly as it can, the script issues commands to:

1. Start Calculator.
2. Switch the focus to Calculator (using the AppActivate method).
3. Send the number 2 to Calculator.

Unfortunately, the script runs faster than Calculator can load. As a result, the number 2 is sent, and the script terminates, before Calculator can finish loading and start accepting keystrokes.

There are at least two ways of working around this problem. First, you might be able to estimate how long it will take an application to load and then pause the script for that amount of time. For example, in this script the Run method is called, and then the script pauses for 5 seconds, giving Calculator time to load:

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "Calc.exe"
Wscript.Sleep 5000
objShell.AppActivate "Calculator"
objShell.SendKeys "2"

Of course, is some cases it might be difficult to estimate how long it will take before an application is loaded and ready to accept keystrokes. In that case, you can call the AppActivate method and check the return value.

Using AppActivate

Before sending keystrokes to an application, you must first ensure that the application is running and that the focus is on the application (that is, the application is running in the active window). You can use the AppActivate method to set the focus on an application. The AppActivate method brings the specified window to the foreground so that you can then start using the WshShell SendKeys method to send keystrokes to the application.

The AppActivate method takes a single parameter that can be either a string containing the title of the application as it appears in the title bar or the process ID of the application. The AppActivate method returns a Boolean value that indicates whether the procedure call has been successful. If the value is False, AppActivate has failed, usually because it was unable to find the application (possibly because that application had not finished loading).

You can place your script in a loop, periodically calling AppActivate until the return value is True. At that point, the application is loaded and prepared to accept keystrokes.

For example, this script checks the return value for AppActivate. If this value is False, the script pauses for 1 second and then checks the value again. This continues until the return value is True, meaning that the application is loaded and ready for use. At that point, the script continues.

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "Calc.exe"
Do Until Success = True
    Success = objShell.AppActivate("Calculator")
    Wscript.Sleep 1000
objShell.SendKeys "2"

When the script is determining which application to activate, the given title is compared to the title of each window visible on-screen. If no exact match exists, the AppActivate method sets the focus to the first window whose title begins with the given text. If a window still cannot be found, the first window whose title string ends with the text is given the focus. The partial matching with the leading and trailing text of title bars ensures that AppActivate works with applications, such as Notepad, that display the name of the currently opened document on the title bar. (For example, when you first start Notepad, the window title is Untitled - Notepad, not Notepad.)

This means that when setting the focus to the Calculator, you can use one of the following lines of code:

objShell.AppActivate "Calculator"
objShell.AppActivate "Calc"
objShell.AppActivate "C"

Of course, this shortcut method of referring to a window can cause problems. For example, suppose you use this line of code:

objShell.AppActivate "Calc"

If you happen to be working on a Microsoft Word document named Calculations.doc, the keystrokes might be sent to the Word document instead of Calculator.

The script in Listing 3.30 demonstrates a more practical use of the SendKeys method: It starts and sets focus to the Microsoft Management Console (MMC) and then sends keystrokes that cause the Add/Remove Snap-in and Add Standalone Snap-in dialog boxes to be displayed. The script automates the first part of the common task of constructing custom MMC snap-in tools.

Listing 3.30 Sending Keystrokes to a GUI Application

Const iNormalFocus = 1
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "mmc.exe",iNormalFocus

Wscript.Sleep 300

objShell.AppActivate "Console1"
Wscript.Sleep 100
objShell.SendKeys "^m"
Wscript.Sleep 100
objShell.SendKeys "{TAB}"
Wscript.Sleep 100
objShell.SendKeys "{TAB}"
Wscript.Sleep 100
objShell.SendKeys "{ENTER}"

What's New In WSH 5.6

Several areas of functionality have been addressed in this latest version of the Windows Script Host (version 5.6). Comparison table that lest features added to the new version can be found at WSH Version Information

Setting up Remote WSH

Remote WSH, which is a new technology included in WSH 5.6, provides the ability to run a script on a remote machine or machines. With Remote WSH, the script is physically copied from the local machine to the remote machine before executing. In order to enable Remote WSH functionality, you must first set up the remote machine with the proper security settings. The steps below perform the tasks that enable Remote WSH.

Recommended Links

Google matched content

Softpanorama Recommended

Top articles




Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy


War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes


Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law


Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D

Copyright © 1996-2021 by Softpanorama Society. was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site


The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March 12, 2019