As you saw in the previous sections, batch files give you a means to automatically run programs. There is some limited programming capability; that is, you have the means to take different actions depending on the conditions encountered , but for the most part, as helpful as they are, batch files just let you push data into and pull data out of existing programs. Scripts, on the other hand, give you access to full-scale programming languages that can more easily manipulate data, and from which you can not only run existing command-line programs, but can also
The range of what you can do with scripting is pretty much limited only to your imagination and your skill as a programmer. And that's the rub, as it does take some training and practice to build up that skill. Scripting is a complex subject that could easily fill several books of this size , so here we'll just be able to scratch its surface. I'll give you an overview. And, I hope that you'll be intrigued enough to learn more through other books and resources. I'll give you some suggestions for follow-up reading at the end of this chapter. Script LanguagesWindows scripting is managed through a program called Windows Script Host or WSH. The word "host" here is significant. It refers to the fact that Windows Script Host is a "framework" program that provides support for scripting without being tied to a specific script programming language. Out of the box, Windows comes with the VBScript and JScript languages, so you can use whichever of these two programming languages you prefer. Or, if you're already more familiar with one of the other programming languages available from third-party vendors , you can download and install one of these other languages, usually for free. Table 9.15 lists several widely used languages for which WSH versions are available. Table 9.15. Windows Script Host Languages [*]
Note Windows Script Host is installed by default with Windows XP and 2000. For Windows 98 and Me you must download it from microsoft.com; search for "download windows script 98." At the time this was written, version 5.6 was the current version. Unix and Linux enthusiasts loudly sing the praises of Perl and Python, and in fact each of the languages has its disciples, but for a first-time programmer, VBScript is probably the easiest of these languages to learn. If you use Microsoft desktop applications, VBScript is definitely an important language to know because it's used inside Word, Excel, Accessin fact most Microsoft productsas the built-in macro language. You'll get a double payoff for learning VBScript because experience you gain writing scripts will help you write macros, and vice versa. With this in mind, for this chapter, I'll provide the examples in VBScript. Creating and Editing ScriptsScripts are plain text files with a special file extension that tells Windows Script Host what language the script is written in; the most common extensions are listed in Table 9.1. The two most common are .VBS for a VBScript script, or .JS for a JScript script. As stated previously, I suggest that you create a special folder to hold your scripts and batch files, for example c:\bat , so that you can put this folder into the search path and thus have access to them from any command prompt. For instructions, see "Creating and Editing Batch Files" earlier in this chapter. When you've done this, open a command prompt window and type the command bat to change to your batch file directory. It's easy to create and edit scripts using the Notepad accessory . Let's create a simple script to display your logon ( user ) name . In the command prompt window you just opened, type notepad myname .vbs and press Enter. When Notepad asks whether you want to create a new file, click Yes. Then, type the following lines into the Notepad window: set wnet = CreateObject("WScript.Network") uname = wnet.UserName wscript.echo "Your user name is " & uname Save the file by clicking File, Save, or equivalently, by typing Alt+F, and then Alt+S. Now, type the following line in the command prompt window: cscript myname.vbs This will run your script as a console (command line) application, and the result will print out in the console window. In my case, it prints: Your user name is brian Now, type the command wscript myname.vbs This runs your script as a Windowed (GUI) application. Instead of printing text at the command prompt, a dialog box pops up, as shown in Figure 9.10. Figure 9.10. The WScript command runs scripts as GUI applications, and text output is displayed in dialog boxes.
In most cases, it's easier to run script applications using the command-line interface. You can set cscript to be the default, so that it is used to automatically run a script when you enter only its name. To do this, enter this command at the command prompt: cscript //nologo //h:cscript //s being sure to double-up the slashes as shown. You only need to do this once; this setting will "stick" permanently. Now, you can run a script simply by typing its name. Type the command myname and press Enter. Recall that .VBS is in the PATHEXT list of executable file types, so when Windows looks for a program named myname it finds myname.vbs , and uses cscript to run it. Note If you have Microsoft AntiSpyware or another antispyware package installed, running a script by name may trigger a security warning. Click the appropriate button to allow the script to run. You may need to retype the command to get the script run. You should only have to go through this once for each new script you write. Security IssuesWhen you run a script (or batch file, or any other program, for that matter), the script can do anything that your user account's permissions let it do. If you are using a Computer Administrator account, this means the script can do anything , including deleting Windows entirely. You should take a moment to consider what might happen if some other user was able to modify your script file to so something other than what you intended. The next time you run the script, it will run with your account's permissions. Another user could use this technique to have you inadvertently give him or her Administrator privileges, cause damage, or, well...the mind boggles. Here's what you can do to prevent this from happening:
Running ScriptsAs I mentioned in the previous section, if the folder that contains your scripts is listed in the PATH environment variable, and if you've set cscript (the command line version of Windows Script Host) to be the default script processor, you can run your scripts just as you would any other Windows command, by typing its name. If your script contains a programming error, Windows Script Host may either refuse to run it, or may stop in the middle of running it. Let's demonstrate this. Open a Command Prompt window and switch to your scripts directory (type bat , if you're using the method I suggested). Edit the sample script by typing notepad myname.vbs , and add on to the third line so that it reads wscript.echo "Your user name is " & uname & " no closing quote here Save the file, and run it again by typing myname at the command prompt. This time you will see this message: C:\Documents and Settings\brian\myname.vbs(3, 68) Microsoft VBScript compilation error: Unterminated string constant This message tells us three things:
When errors like this occur, you'll need to determine what's wrong with the script before you can continue. The description of the message will often help you figure out what's wrong; you may have this sort of "syntax error," that is, there may be a missing keyword, quotation mark, or other typographical error, or the program might be attempting to work with invalid data. Tip To view and edit the script line that caused the error, open the script with Notepad. Turn line wrapping off by clicking Format and unchecking Word Wrap. (You just need to do this once; it will still be unchecked the next time you run Notepad.) Now, press Ctrl+G. Windows will pop up the Goto Line dialog. Type the line number reported by Windows Script Host (3, in the example you just saw), and press Enter. This will move the cursor right to the offending line. Scripting and COM ObjectsAlthough the programming languages that you can use with Windows Script Host are powerful programming tools by themselves , most of their usefulness comes from their ability to work with external software components called Component Object Model (COM) objects . In the most general sense, objects are little program packages that manipulate and communicate information. They're a software representation of something tangible , such as a file, a folder, a network connection, an email message, or an Excel document. You interact with objects through their properties and methods . Properties are data values that describe the attributes of the thing the object represents. For example, a file or folder object might have a name property that represents the associated file or folder's name. Methods are actionsprogram subroutinesyou can use to alter or manipulate whatever the object represents. For example, a file object might have a delete method that, if activated, would delete the associated file. Most importantly, objects extend the abilities of the language from which they're used. Although VBScript doesn't know how to manage network printers, it does know how to let you use a COM object that can manage network printers. Hundreds of different COM objects are available in Windows, representing things like network connections, files and folders, printers, user accounts, email messages, and Active Directory information. In addition, many application programs such as Word and Excel are totally accessible as COM objects themselves, so if you have Microsoft Office or another desktop suite installed, your scripts can create documents, spreadsheets, and charts . In VBScript, the statement used to create an instance of a particular object is set variable = CreateObject(" objectname ") where variable is the name of the variable you want to use to refer to the object reference, and objectname is the type of object you want to create. Once an object has been created, you refer to its properties and methods as variable.name , where variable is an object variable, and name is the name of a method or property. Let's look again at the sample script you created at the beginning of this section on scripting: set wnet = CreateObject("WScript.Network") uname = wnet.UserName wscript.echo "Your user name is " & uname The first line creates a WScript.Network object, and stores it in variable wnet . WScript.Network objects provide properties and methods for working withyou guessed itWindows networking. The second line sets a normal VBScript variable with the value of the object's UserName property, which is the name of the currently logged-on user. The third line uses the built-in WScript object, an object that is automatically provided by Windows Script Host. Its echo method prints whatever text is provided on the program line into the console window or a dialog box (depending on whether the script is being run as a console program with cscript or a GUI program with wscript ). The point I want to make here is that VBScript itself doesn't know how to determine your username, but Windows comes with a component called the WScript.Network object that does. And, there are thousands of object types provided with Windows. Some of the most important objects used for management scripting in Windows Script Host are listed in Table 9.16. Table 9.16. Some Windows Management COM Objects
In addition, applications such as Microsoft Word and Excel provide objects such as Word.Document and Excel.Sheet . You can create and manipulate these objects as well; for instance, a script could easily create a telephone directory Word document by pulling information out of Active Directory. Sample ScriptsHere are a few practical scripts that demonstrate the kinds of things you can accomplish with scripting in Windows. They range from information gathering to workflow management. Listing Network Printer ConnectionsThe following script, listprinters.vbs , lists the computer's printer mappings: set wshNetwork = CreateObject("WScript.Network") set maps = wshNetwork.EnumPrinterConnections for i = 0 to maps.Length-2 step 2 WScript.echo "Port:", maps.item(i), " Name:", maps.item(i+1) next The output on my computer looks like this: Port: USB002 Name: Samsung ML-1710 Series Port: Microsoft Document Imaging Writer Port: Name: Microsoft Office Document Image Writer Port: HPLaserJet4V Name: HP LaserJet 4V JetDirect Port: SHRFAX: Name: Fax Port: C:\Documents and Settings\All Users.WINDOWS\Desktop\*.pdf Name: Acrobat Distiller Reading and Writing Registry ValuesThe following script, countme.vbs , shows how a script may read and write Registry values. This demonstration script just prints a running count of how many times it has been run. set shell = CreateObject("WScript.Shell") nruns = shell.RegRead("HKCU\Software\MyScripts\countme\number of runs") nruns = nruns+1 wscript.echo "Number of runs:", nruns Shell.RegWrite "HKCU\Software\MyScripts\countme\number of runs", nruns, "REG_DWORD" If you create this script and type countme countme countme at the command prompt, you'll see the count increase by one each time. In addition, if you use regedit to view key HKEY_CURRENT_USER\Software\MyScripts\countme , you'll see that the program indeed saves a value in the Registry (click View, Refresh after running countme to see that the value changes). Sending Email from a ShortcutFinally, there is a long-ish but practical script meant for someone who regularly has to email files to a colleague as part of their day-to-day job. With this script, you can simply drag files on the Desktop and drop them onto a shortcut icon, and they'll be mailed without your having to do anything else. The script takes any files named on its command line and sends them to a specific person as email attachments. To use this script, you would first edit it to use the correct email addresses, and you'll need to add the name of your organization's SMTP mail server (the server for outgoing mail). Then, create a shortcut to the script on your desktop. When you drop files on a shortcut, Windows runs the associated program with the names of the dropped files as command-line arguments. In our case, the program is the following script. It uses the Collaboration Data Objects (CDO) tool provided with Windows 2000 and XP. if WScript.arguments.count <= 0 then ' no files were specified MsgBox "Usage: mailfiles filename..., or drag files onto shortcut" WScript.quit 0 end if const cdoSendUsingPort = 2 ' standard CDO constants const cdoAnonymous = 0 sender = "brian@mycompanyxyz.com" ' sender of message recipient = "sheila@mycompanyxyz.com" ' recipient of this message subject = "Attached: sales lead form" set msg = CreateObject("CDO.Message") ' create objects set conf = CreateObject("CDO.Configuration") set msg.configuration = conf With msg ' build the message .to = recipient .from = sender .subject = subject .textBody = "Attached to this message are files for you." nfiles = 0 ' count of files attached for each arg in WScript.arguments ' treat each argument as a .AddAttachment arg ' file to be attached nfiles = nfiles+1 next End With prefix = "http://schemas.microsoft.com/cdo/configuration/" With conf.fields ' set delivery options .item(prefix & "sendusing") = cdoSendUsingPort .item(prefix & "smtpserver") = "mail.mycompanyxyz.com" .item(prefix & "smtpauthenticate") = cdoAnonymous .update ' commit changes End With on error resume next ' do not stop on errors msg.send ' deliver the message on error goto 0 ' restore normal error handling if err then ' if something went wrong.... MsgBox "Error sending message" else if nfiles = 1 then plural = "" else plural = "s" MsgBox "Sent " & nfiles & " file" & plural & " to " & recipient end if Learning More About ScriptingUseful scripting is at first a complex undertaking, as you have to learn about programming and about Windows management scripting tools at the same time. It's far too much to cover in a single chapter of single book; I've just tried to give you a taste. For more in-depth coverage of the command line, batch files, and scripting, check out Brian's book Windows XP Under the Hood: Hardcore Scripting and Command Line Power , published by Que, which is a tutorial as well as a handy desk reference. For a detailed reference to all VBScript statements, functions, objects, and constants, see the online or downloaded version of the VBScript Language Reference, which you can get at msdn.microsoft.com/scripting. Finally, I've found that some of the Microsoft public newsgroups can be a great source of information for everyone from beginners to old hands. The newgroups microsoft.public.scripting.vbscript and microsoft.public.scripting.wsh are particularly valuable . You can learn a lot by watching the discussions, and unlike most newsgroups I've tried, in these you have a reasonably good chance of getting a useful answer if you post a concise , realistic question. Although some of the conversation on these newsgroups concerns the use of VBScript in web server and web browser applications, most of the discussion is applicable to scripting as well. |