Tải bản đầy đủ (.pdf) (10 trang)

Microsoft WSH and VBScript Programming for the Absolute Beginner Part 8 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (334.37 KB, 10 trang )

50
Only the Windows .NET, XP, 2000, and NT operating systems support event
logs. Don’t try running this script on other Windows operating systems such as
Windows 98 or Me.
The scripting logic to write a message to the Windows application event log is very simple:
Set WshShl = WScript.CreateObject(“WScript.Shell”)
WshShl.LogEvent 0, “EventLogger.vbs - Beginning script execution.”
The first line of this script establishes an instance of the WshShell object. The second line
uses the
WshShell object’s LogEvent() method to write a message to the event log.
One really good use of the WshShell object’s LogEvent() method is to log the
execution of scripts run using the Windows Event Scheduler service. This way,
you can review the application event log each day and make sure that your
scripts are executing when you expect them to.
Using your script editor, create a new script called EventLogger.vbs that contains the previ-
ous statements. Run the script and then check the application event log; you should find
the message added by the script. Double-click it; you should see the Event Properties dialog
for the event, as shown in Figure 2.11.
HINT
TRAP
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 2.10
Examining the
contents of the
application
event log.
Configuring WSH Execution Hosts
So far you’ve used the CScript and WScript execution host default settings for each script
that you’ve created and run. If you want to, you can modify these default settings to better
suit your personal preferences. The WSH provides separate configuration settings for the
WScript and CScript execution hosts. Because the WScript execution hosts can process


scripts run from either the Windows GUI or the Windows command line, there are two dif-
ferent ways to configure them. The WSH also allows you to override execution host settings
on-the-fly by passing configuration arguments to the execution host when starting a script’s
execution. Finally, the WScript execution host allows you to set execution host settings
unique to a particular script using a
.wsh file.
Each of these execution host configuration options is examined in detail in the sections that
follow.
Configuring WScript and CScript Command-Line Execution
You can use either the WScript or CScript execution hosts to run any VBScript. Generally
speaking, you’ll use the WScript to run scripts that need to use pop-up dialogs, and the
CScript execution host to run scripts silently in the background.
51
Chapter 2 • Overview of the Windows Script Host
Figure 2.11
Viewing the event
that the
EventLogger.vbs
script added to
the Windows
application
event log.
52
Even though they have their own separate configuration settings, both the WScript and
CScript execution hosts are configured in the same way, using the exact same set of options.
The syntax used to configure these two execution hosts is as follows:
wscript [//options]
cscript [//options]
Begin by opening a Windows Console. From the Windows command prompt, type the name
of the execution host that you want to configure followed by one or more options, each of

which is preceded by the
// characters.
Any changes that you made to the default execution host will only affect your
scripts—if you share a computer with somebody else, his or her WSH execution
host settings will not be affected. If you want WSH settings to be standardized
for all users of the computer, make sure that each user sets them accordingly.
Table 2.5 lists the configuration options supported by the WScript and CScript execution
hosts.
Now let’s look at some examples of how to modify the configuration of the execution hosts.
By default, the WSH sets the WScript execution host up as the default execution host. How-
ever, you can change this by typing the following command and pressing the Enter key:
cscript //H:cscript //s
The //H:cscript option makes the CScript execution the default and the //s option makes
the change permanent. If you left the
//s option off the command, the change would have
only been in effect for your current working session. Likewise, to change the default command-
line execution host back to WScript, type the following command and press the Enter key:
wscript //H:wscript //s
Now let’s try an example that sets more than one configuration option:
wscript //H:wscript //nologo //t:60 //s
In this example, the WScript execution host is set up as the default. In addition, the //nologo
option prevents the display of the WScript logo during script execution. The //t:60 option
prevents any script from executing for more than 60 seconds. Finally, the
//s option saves
all specified settings.
TRAP
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Even the best programmers can make mistakes. Sometimes these mistakes
cause scripts to behave in unexpected ways, such as getting stuck in a loop that
executes forever. By setting the //T:nn option for both the WScript and CScript

execution hosts, you can set up a sort of safety net that prevents any script that
you run from executing for more than a minute.
Configuring WScript Desktop Execution
The WScript execution host’s desktop configuration settings are different from its command-
line configuring settings. First of all, there are only two configuration settings. The first
specifies an optional time limit for script execution, and the second specifies whether or
not the WScript logo is displayed when scripts are run from the Windows Console.
TRICK
53
Chapter 2 • Overview of the Windows Script Host
Configuration Option Purpose
//? Displays the command syntax for the CScript and WScript
execution hosts.
//b Runs a script in batch mode, where all errors and message output
are suppressed.
//d Turns on script debugging.
//e:jscript | e:vbscript Sets the script engine that is to be used to run the script.
//h:wscript | h:script Sets the execution host that is to be used to run the script.
//i Runs the script interactively, displaying all errors and message output.
//job:id Identifies a specific job within a Windows script file to be run.
//logo Displays the CScript or WScript logo at the start of script execution.
//nologo Suppresses the display of the CScript or WScript logo at the start
of script execution.
//s Saves the currently specified options and sets them as the default
settings.
//t:nn Establishes a timeout value that limits how long a script can
execute. By default, these are not execution time limits imposed
on script execution.
//x Turns off script debugging.
TABLE 2.5 COMMAND-LINE O PTIONS FOR THE WSCRIPT

AND
CSCRIPT E XECUTION H OSTS
54
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
The steps involved in configuring the WScript execution host from the Windows desktop are
as follows:
1. Click on Start, Run. The Run dialog appears.
2. Type
WScript and then click on OK. The Windows Script Host Settings dialog appears,
as shown in Figure 2.12.
3. As you can see, by default, the WScript execution host does not have an execution
time setting. To configure one, select the Stop script after specified number of sec-
onds option and then specify a time limit (in seconds).
4. By default, the WScript execution host displays its logo when scripts are executed
from the Windows Console. To prevent this behavior, clear the Display logo when
script is executed in command console option.
5. Click on OK.
Overriding Command-Line Host Execution Settings
So far, you’ve learned how to configure the default execution of the WScript and CScript
execution hosts from the Windows command-line and desktop. Now let’s see how to over-
ride the default command-line settings without permanently changing them, in order to
temporarily alter them for the execution of a specific script.
Figure 2.12
Modifying the
WScript
execution host’s
desktop
configuration.
The syntax for temporarily overriding WScript and CScript execution is as follows:
wscript scriptname [//options] [arguments]

cscript scriptname [//options] [arguments]
First, open the Windows Console, and then type the name of the execution host you want
to use to run the script. Next, type the name and path of the script to be executed; then type
as many configuration settings as you want, preceding each with a pair of
// characters.
Finally, if the script that you’re executing expects any input to be passed to it at execution
time, specify the required arguments and then press
the Enter key.
Now let’s look at a few examples of how to override
host script execution settings. First, let’s assume that
you’re working with a script called
Test Script.vbs
and that you want to prevent it, using the WScript exe-
cution host, from executing for more than 30 seconds.
Open the Windows Command Console and type the
following command to run the script using the
WScript execution hosts:
wscript “Test Script.vbs” //T:30
Likewise, to execute the same script using the CScript execution host for a maximum of 30
seconds, type the following command, and then press the Enter key:
cscript “Test Script.vbs” //T:30
Windows operating systems support very large file names. They also allow you
to include blank spaces as part of a file name to make those names more
descriptive. If you choose to include blank spaces as part of your VBScript file
names, then you’ll need to enclose the file names inside a pair of quotation
marks, as shown in the two previous examples, so that the script’s file name will
be correctly interpreted.
Now let’s look at a slightly more complicated example, in which multiple configuration
settings are overridden:
wscript “Test Script.vbs” //T:30 //nologo

In this example, the script is prevented from executing for more than 30 seconds using the
WScript execution hosts. In addition, the WScript execution host’s logo is suppressed to pre-
vent it from being displayed at the beginning of the script’s execution.
TRAP
55
Chapter 2 • Overview of the Windows Script Host
Definition
In the context of this discussion, an
argument is a piece of data passed
to a script for processing. For
example, if you wrote a VBScript to
create new user accounts, your
script might expect you to pass it
one or more usernames to process.
56
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Customizing WScript Settings for Individual Desktop Scripts
The WSH also provides a way, using the WScript execution host, to permanently override
configuration settings for specific scripts run from the Windows desktop. This is done by
creating a text file with the same name as the script and giving the file a
.wsh extension.
Then, within the
.wsh file, you can specify specific WSH configuration settings. For exam-
ple, to set up a
.wsh file for a script named Test Script.vbs, you would create a file called
Test Script.wsh and save it in the same folder in which the Test Script.vbs script resides.
You could then run the script by double-clicking on
the .wsh file or by double-clicking on
the script itself. If you double-click on the
.wsh file, the WSH automatically finds the script

that is associated with it, and, after processing the configuration settings stored in the
.wsh
file, runs the script. Conversely, whenever you double-click a script, the WSH first looks to
see if it has an associated
.wsh file before running it; if it does not, then the WSH processes
it using the execution host’s default configuration settings.
The following statements show the contents of a typical
.wsh file:
[ScriptFile]
Path=C:\Test Script.vbs
[Options]
Timeout=30
DisplayLogo=0
The first line contains the section label called [ScriptFile]. The next statement provides the
name and path of the script associated with this
.wsh file. Next comes an [Options] section
label. The last two lines contain configuration settings specific to the execution of this
script.
Timeout=30 specifies that this script will not be allowed to process for more than 30
seconds, and
DisplayLogo=0 specifies that the WScript logo is to be suppressed. An alterna-
tive setting for this option would be
DisplayLogo=1, which would enable the display of the
WScript logo.
There are two ways to create a
.wsh file. One way is to use a text editor, such as the Windows
Notepad application, to manually create the file. The other option is to let Windows create
the
.wsh file for you using the following procedure:
1. Locate the folder in which the VBScript is stored.

2. Right-click on the script and select Properties from the menu that appears. The
script’s Properties dialog appears, as shown in Figure 2.13.
3. Click on the Script property sheet, as shown in Figure 2.14.
57
Chapter 2 • Overview of the Windows Script Host
Figure 2.13
Examining the
properties on the
General property
sheet of the
scripts properties
dialog.
Figure 2.14
Creating a .wsh
file via a script’s
Properties dialog.
58
4. Specify a script execution time limit, as required.
5. Enable or disable the display of the WScript logo as desired.
6. Click on OK.
A new
.wsh file is then created for you and stored in the same folder as the script.
Back to the Rock, Paper, and Scissors Game
Now it’s time to go back to where this chapter started—talking about the Rock, Paper, and
Scissors game. In this project, you will create a scripted version of this classic game. This ver-
sion is a bit limited, given that you’ve not had the chance yet to learn everything you’ll need
to create a more sophisticated version. However, you know enough to build the game’s foun-
dation and get a working model going. In Chapter 5, “Conditional Logic,” you’ll get the
chance to return and spice things up a bit.
Designing the Game

The basic design of this game is simple. First, display the rules of the game, and then ask the
player to type rock,
paper, or scissors. Next, have the script randomly pick a choice of its
own and display the results.
This project is completed in six steps:
1. Define the resources used by this script.
2. Display the game’s instructions.
3. Provide a way for the user to select a choice.
4. Devise a way for the script to generate a random number.
5. Assign the computer’s choice based on the script’s randomly selected number.
6. Display the final results of the game.
Defining the Resources Used by the Script
Begin by opening your editor and saving a blank file with a name of RockPaperScissors.vbs.
Next, add the first few lines of the script as follows:
‘Formally declare variables used by the script before trying to use them
Dim WshShl, Answer, CardImage
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
‘Create an instance of the WScript object in order to later use the
‘Popup method
Set WshShl = WScript.CreateObject(“WScript.Shell”)
The first line begins with a ‘ character. This character identifies a VBScript comment. Com-
ments can be used to document the contents of scripts. Comments have no affect on the exe-
cution of a script. The next line begins with the VBScript keyword
Dim. This statement
defines three variables that will be used by the script. A variable is simply a portion of the
computer memory where your scripts can store and retrieve data. I’ll provide more infor-
mation about variables and how they work in Chapter 4, “Constants, Variables, and Arrays.”
The third statement is another comment, and the fourth statement uses the
WScript object’s
CreateObject() method to set up an instance of the WshShell object. This statement allows

the script to access
WshShell properties and methods.
Displaying the Rules of the Game
Next, let’s take advantage of the WshShell object that you just defined by using its Popup()
method to display a message in a graphical pop-up dialog:
‘Display the rules of the game
WshShl.Popup “Welcome to Rock, Paper and Scissors game. Here are the “ & _
“rules of the game: 1. Guess the same thing as the computer “ & _
“to tie. 2. Paper covers rock and wins. 3. Rock breaks “ & _
“scissors and wins. 4. Scissors cut paper and wins.”
This is really just two lines of code, although it looks like five. The first line is a comment.
However, the second line was so big that I chose to break it down into multiple pieces for
easy display. To do so, I broke the message that I wanted to display into multiple segments
of similar lengths, placing each segment within a pair of quotation marks. To tie the dif-
ferent segments into one logical statement, I added the VBScript
& character to the end of
each line, followed by the
_ character.
Collecting the Player’s Selection
When the player clicks on OK, the pop-up dialog displaying the game’s rules disappears and
is replaced with a new pop-up dialog that is generated by the following code:
‘Prompt the user to select a choice
Answer = InputBox(“Type Paper, Rock, or Scissors.”, _
“Let’s play a game!”)
59
Chapter 2 • Overview of the Windows Script Host

×