|
9.3. Development TipsAs you develop WSH scripts, you'll quickly discover that you'll need more than just ephemeral knowledge of the commands and references to complete most tasks. Windows is a complex system, and your scripts don't exist in a vacuum. The rest of the solutions and examples in this chapter will help you write scripts that operate in the broader context of the fully functioning Windows XP environment. 9.3.1. Deciphering Script ErrorsOne of the general disadvantages of scripts is that they are typically created with a plain-text editor, rather than a rich debugging environment used with many more sophisticated programming languages (see Section 9.3.2 later in this chapter). Because Notepad isn't specifically designed to understand VBScript, it can't offer any assistance with syntax (grammar) or errors while you're editing. Therefore, you must wait until you run the script to see if there are any problems. If WSH encounters an error, it will display a message similar to that shown in Figure 9-2. Figure 9-2. The Windows Script Host displays a message like this whenever it encounters an errorSurprisingly, this sparse message box actually provides enough information to resolve most problems. Naturally, the first field, Script, shows the script filename in which the error occurred. This is especially useful if the script was run from a scheduled task or from your Startup folder, and you might not otherwise know which script caused the error. The Line field shows on which exact line of your script the error occurred and includes blank lines and remarks. Likewise, the Char field shows the column of the first character of the cause of the error, including any indent.
The Source field describesmore than anything elsewhat the WSH engine was doing when it encountered the error. A compilation error occurs when WSH is first reading the file and making sure all of the commands are correctly entered; you'll see this if you forgot a parenthesis or quotation mark, misspelled a command, or left out some other important keyword. A Microsoft VBScript runtime error, on the other hand, is an error encountered while the script was being executed; this is caused by errors that WSH doesn't know are errors until it actually tries them, such as trying to read from a file that doesn't exist or trying to calculate the square root of a negative number. Lastly, the Error field shows a brief explanation of the error encountered, and the Code field shows the corresponding numeric error code (useful for searching Google or the Microsoft Knowledge Base if you can't figure out the problem yourself). Sometimes the error description is helpful, but most of the time it's either too vague or too cryptic to be of much help. This is where programming experience comes in handy for interpreting these messages and figuring out what caused them. The following are a few of the more common Error descriptions and what they mean:
If you plan on distributing your scripts, you'll want to take steps to eliminate any error messages that may pop up. See the Section 9.2.3 script earlier in this chapter for more information on error trapping and the On Error Resume Next statement. 9.3.2. Finding a Better EditorNotepad is a very rudimentary text editor. Although it serves our purpose, allowing us to write and save VBScript files, it doesn't go any further than it absolutely needs to. It has no toolbar, no syntax highlighting, no visible line numbers, and no macro feature. If you find yourself writing VBScript files often, you'll want to use a better editor. Now, Windows also comes with WordPad, although it doesn't do much more than Notepad in helping to write scripts, and it has that creepy Microsoft Word-like interface. One direction to go is simply to use a better plain-text editor, such as UltraEdit-32 (http://www.ultraedit.com). It has many features prized by programmers, such as column selections, visible line numbers, a terrific multi-file search-and-replace, and many other goodies. However, it's still just a text editor and therefore doesn't provide any VBScript-specific assistance. Most full-featured programming languages come with a rich programming environment that provides real-time syntax checking (similar to a spellchecker in your word processor; some even tell you right away if you missed a parenthesis), as well as context-sensitive help (you can get technical assistance as you're typing code). The problem is that Windows doesn't come with such an editor, nor am I aware of any decent VBScript editor at the time of this writing. Some may suggest that you can use either the Visual Basic editor or the VBA editor that comes with Microsoft Office 97 or Office 2000 to write your scripts, but this should be taken with a grain of salt. Although VB and VBA do have a similar syntax to VBScript and even share many commands, the environments are different enough that it's more trouble than it's worth. 9.3.3. Further StudyGiven that writing scripts for the Windows Script Host is a language-dependent endeavor, the most helpful reference material will be specific to the particular language you're using. Microsoft's support web site for all their scripting technologies, including WSH, can be found at http://msdn.microsoft.com/scripting/. In addition to documentation on VBScript and JScript, you can download updates to the WSH engine. Note that if you distribute scripts to other machines, you'll need to be careful about supporting features found only in newer releases of WSH. Before committing to VBScript for a project, you may want to do some research on other supported languages listed here. Due to VBScript's heritage in web pages, security concerns have resulted in some limitations in the VBScript language, such as its inability to access the clipboard or link to external .dll files. Given that JavaScript (which actually has nothing whatsoever to do with Sun Microsystems' Java programming language) was created by Netscape, you can find a lot of developer information at: http://developer.netscape.com/tech/javascript/. Keep in mind, however, that JScript is Microsoft's bastardized version of JavaScript and therefore not exactly the same language. The Practical Extract and Report Language (Perl) is probably the most powerful and flexible scripting language available for the Windows Script Host at the time of this writing. It's traditionally very popular among the Unix crowd and has gained tremendous popularity for its use in writing CGI programs for web servers. Unfortunately, Windows XP doesn't come with the Perl engine; you'll have to obtain a separate Perl add-on module from http://www.activestate.com. More information is available at http://www.perl.com. 9.3.4. Making a Startup ScriptThe process of making a startup scripta script that is executed automatically when Windows startsis quite simple. Essentially, you create a script as you normally would, and then take steps to have it executed when Windows starts. There are a few different ways to do this:
A startup script can contain a list of programs that you want run in a specific order when Windows starts, such as connecting to the Internet and then checking your email. (Neither Explorer's Startup folder nor the Registry allow you to choose the order in which programs are run.) But there are other, less apparent uses for a startup script, such as for security or remote administration. For example, say you've discovered a virus that has infected some or all the computers on a network. By writing a script that eliminates the virus by deleting key files or running an antivirus utility automatically with a startup script, you can effectively eliminate the virus from each computer. But with scripts, you can take it even further: utilize a single script stored on a single computer that is run over the network on all computers. This way, you can make changes to the script once and have those changes propagated to all computers effortlessly. So, if you place the script Startup.vbs on a machine called Server in a folder called c:\scripts (drive c: would be shared as "c"), then each client machine should be configured to automatically execute \\server\c\scripts\startup.vbs (using one of the previous methods). The beauty of this is that when you don't want the script to do anything, you can simply leave it intact yet empty. If you find that you need to, say, make a Registry change or copy a group of files onto each computer, just type the appropriate commands into the script and turn on (or reboot) all the client computers. This can turn some administration tasks into very short work. 9.3.5. Automating Scripts with Scheduled TasksThe Scheduled Tasks feature is fairly simple, allowing you to schedule any program ormore importantly in the context of this chapterany script. What's nice about the Scheduled Tasks feature is that it's actually a technology that is somewhat well integrated into the operating system. Any application can create a schedule for itself, and you can plainly see those that are in effect simply by opening the Scheduled Tasks folder. For the more forgetful among us, you can use it to schedule Disk Defragmenter to run once a month, Backup to run once a week, or Windows Update to check for new updates every morning. The Scheduled Tasks feature also has its pitfalls. The Add Scheduled Task tool is cumbersome and very limited. It's also a rather passive service, and while that's an aspect I like, at least idealistically, it means that tasks can very easily be missed. Any scheduled tasks will not be performed if you've selected the Stop Using Task Scheduler option (in the Advanced menu), if your computer is turned off, if Windows isn't running, or if your portable computer is running off its battery. These situations may be obvious, but they can be easy to forget, and Windows will only tell you if you missed any tasks if you manually enable the Notify Me of Missed Tasks option. There are several ways to create a new scheduled task, the most obvious of which is to double-click the Add Scheduled Task icon in the Scheduled Tasks folder. The overly verbose wizard should then walk you through the process of creating a new task. When the wizard prompts you to select a program (it just displays a list of all the applications listed in your Start Menu), click Browse, select an existing script or other application on your hard disk, and click OK when you're done. At this point, I recommend just clicking Next repeatedly here until the wizard is finished. Then right-click on the new task, and select Properties to configure the task with a more suitable and convenient tabbed interface. Fortunately, there is a shortcut you can use to bypass the wizard entirely: just go to File New and then Scheduled Task. Then, right-click the new task, and select Properties. Finally, you can create a new task on the fly from the command prompt (or the Address Bar). Use the at command, like this: at 11:15 /interactive c:\scripts\myscript.vbs Naturally, you'll want to replace 11:15 with the time you actually want the task to run, and replace c:\scripts\myscript.vbs with the full path and filename of the application or script you wish to schedule. You can also use the /every option to specify a repeating day or date, or the /next option to specify only a single day: at 15:45 /interactive /every:tuesday,thursday c:\scripts\myscript.vbs at 15:45 /interactive /next:saturday c:\scripts\myscript.vbs Type at /? at the command prompt for more options, or see Windows XP in a Nutshell (O'Reilly) for full documentation. One thing to note is the two Power Management settings in the Settings tab of the Task's Properties dialog box. By default, tasks won't be run if your computer is running on batteriesa setting you may want to change if you need the task performed regardless of your computer's power source. The use of a scheduler opens up some interesting possibilities. Scheduling helps with repetitive chores, such as running Disk Defragmenter or synchronizing network files; it also helps by taking care of things you may not remember to do yourself, such as backing up or sending an email to your grandmother on her birthday. See the following topics for more ideas. |
|