As 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.
One 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.
Surprisingly, 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.
If you’re using Notepad, select Status Bar from the View menu to display the line number (Ln) and column (Col) at which the insertion point (text cursor) is resting. Or, select Go To from Notepad’s Edit menu to quickly jump to any line. Better yet, switch to a better text editor (discussed later in this chapter) that has line numbering and other handy debugging tools.
The Source field describes—more than anything else—what 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:
Compilation error: you left out a closing parenthesis,
such as at the end of an InputBox
statement (see earlier). Note
that sometimes you can have nested parentheses (e.g., x=1+(6+7*(3-4))
), and you need to make
sure you have an equal number of open and close
parentheses.
Compilation error: you left out a closing statement for a
structure, such as If
,
Sub
, or For
. Make sure you include End
If
, End
Sub
, and Next
, respectively. Note that WSH
might report that the error occurred on line 37 of a 35-line
file; this happens because in looking for a closing statement,
WSH continues to search all the way to the end of the script, at
which time, if the statement was not found, it will report the
error. You’ll have to look through the entire script for the
unpaired beginning statement. See the topics on flow control
earlier in this chapter (Section 9.1.3, Section 9.1.4, and
Section 9.1.5)
for more information on these commands.
Compilation error: you left out a closing quotation mark, usually required at the end of a “string of text.”
Runtime error: this usually means that a subroutine or function has been called with one or more improper parameters. This can occur, for example, if you try to do something WSH isn’t capable of, such as calculating the square root of a negative number.
Runtime error: this means you’ve tried to use a command or function that VBScript doesn’t recognize. You’ll get this error whenever you try to use a VB command that doesn’t exist in VBScript.
Runtime error: because it can be difficult to find
documentation on the various objects used in VBScript, you’re
likely to encounter this error frequently. It means that you’ve
tried to refer to a property or method of an object (such as
WScript
) that doesn’t exist
(such as WScript.Dingus
).
Runtime error: This error, obviously reporting that you’ve tried to access a file on your hard disk that doesn’t exist, also appears when you try to delete a Registry key that doesn’t exist. See Section 9.2.2 earlier in this chapter for a Registry function that solves this problem.
Runtime error: you’ll get this when you try to use the
Set
statement (as described
throughout this chapter) and, for whatever reason, WSH isn’t
familiar with the object you’re trying to initialize. Typically,
objects are extensions to WSH: some of which come with Windows
XP, some of which are installed through Add or Remove Programs,
and some of which come with third-party programs. The resolution
usually involves installing the missing component (which usually
can be found on the Web) but depends entirely upon the specific
object reported by the error.
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.
Notepad 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.
Given 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.
The process of making a startup script—a script that is executed automatically when Windows starts—is 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:
Put a shortcut to the script in your Startup folder (usually C:Documents and Settings{username}Start MenuProgramsStartup). This is by far the easiest to implement but also the most fragile, because it’s equally easy to disable (important if you’re setting up a computer for someone else).
Open the Registry Editor (see Chapter 3), and expand the
branches to HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionRun
.
Select New and then String Value from the Edit menu, and type startup
script
. Double-click the new Startup
Script
value,
type the name of your script (e.g., c:scriptsmyscript.vbs
), and click
OK. Although a little more
difficult to implement, this setup is a little more robust and
transparent than using the Startup folder.
Many viruses and spyware install themselves in this Registry key precisely because it’s so transparent. See Chapter 6 for tips on how to remove malware from this key.
Likewise, you can implement this solution for all users
rather than just the current user by adding the Registry value
to HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionRun
instead.
This is probably the coolest solution, as it gives you the
most control over precisely when the script is run, and it’s the
only way to facilitate a shutdown or logoff script as well. Open
the Group Policy Editor (gpedit.msc), and expand the branches
to Computer
ConfigurationWindows
SettingsScripts (Startup/Shutdown)
.
Double-click the Startup entry
on the right side, and then click Add. Click Browse to locate a script file, and click
OK when you’re done. The script
will be run every time you start your computer, but before the
logon or Welcome screen appears (and before scripts specified in
the Registry or Start Menu are ever run).
Likewise, double-click the Shutdown entry to specify a script to be run every time your computer shuts down.
Now, there’s a similar folder called Scripts (Logon/Logoff)
, located in the
User Configuration
branch.
Like everything in the User
Configuration
branch, these
settings apply only to the currently logged-on user (as opposed
to all users). If you specify your startup script here (under
Logon
), instead of under
Computer Configuration, the script will run after you log in.
And, of course, a script specified under Logoff will be run when
you log off, whether or not you actually shut down the
computer.
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 \servercscriptsstartup.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.
The Scheduled Tasks feature is fairly simple, allowing you to schedule any program or—more importantly in the context of this chapter—any 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 → Scheduled Task, or right-click an empty area of the Scheduled Tasks folder, and select 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:
at11:15
/interactivec:scriptsmyscript.vbs
Naturally, you’ll want to replace
11:15
with the time you actually want the
task to run, and replace
c:scriptsmyscript.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:scriptsmyscript.vbs at 15:45 /interactive /next:saturday c:scriptsmyscript.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 batteries—a 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.
3.15.137.75