In this chapter, you'll learn how to use a number of VBScript statements that can help you develop scripts capable of processing extremely large amounts of information—in most cases with only a handful of script statements. Using these statements, you'll be able to establish loops within your scripts in order to let the user iteratively enter as much data as needed, to process the contents of array, to read the content's files, and to control the execution of VBScript games. In addition, I'll show you how to create shortcuts for your scripts, as well as how to place them on the Windows desktop, Start Menu, and Quick Launch toolbar. Specifically, you will learn how to
In this chapter's project, you'll create a script that plays a number guessing game. The game will generate a random number between 1 and 100, then instruct the player to try to guess it. As the player enters guesses, the game will provide the player with hints to help him figure out the number. If the player types an invalid guess, the game will let him know that only numeric input is accepted. The player may quit at any time by simply clicking on the Cancel button, or by failing to type a guess before clicking on OK. Once the player guesses the correct answer, the game displays the number of guesses that it took him to find the correct answer. Figures 6.1 through 6.6 provide a sneak peek of the game's interaction.
Figure 6.1: The Guess a Number game begins by prompting the player to type a number between 1 and 100.
Figure 6.2: The game tells the player to try again if his or her guess is too low.
Figure 6.3: The game tells the player to try again if his or her guess is too high.
Figure 6.4: The game instructs the player to provide only numeric input.
Figure 6.5: The game ends if the players clicks on Cancel or fails to provide a guess.
Figure 6.6: Once the player has correctly guessed the game's number, the player is congratulated.
The game will use a VBScript loop to continue executing until either the player guesses the correct answer or quits. By developing and working with this game, you will solidify your understanding of iterative programming while also learning specifically how to apply a loop using VBScript.
One of VBScript's best programming features is its strong support for looping or iterative statements. VBScript provides five different statements that are capable of creating loops. Loops provide your scripts with the ability to process large collections of data using a minimal number of programming statements that are repeatedly executed, either for each member of the collection or for a specified number of times.
Definition
A loop is a collection of statements that are repeatedly executed in order to facilitate the processing of large amounts of data.
The following list provides a high-level description of each of VBScript's looping statements:
The For...Next statement is used to create loops that execute a specific number of times. For example, if you're creating a game that requires that the player enter five guesses, you could use a For...Next loop to control the logic that supports the data collection portion of the script.
The syntax for the For...Next statement is as follows:
For counter = begin To end [Step StepValue] statements Next
Counter is a variable used to control the execution of the loop. Begin is a numeric value that specifies the starting value of the counter variable. End specifies the ending value for the counter variable (that is, the value that, when reached, terminates the loop's execution). StepValue is an optional setting that specifies the increment that the For...Next statement uses when incrementing the value of counter (that is, the value added to counter at the end of each iteration).
To better understand the operation of a For...Next loop, look at one example that collects data without using a loop and one that collects the same data using a For...Next loop. In the following example, let's assume that you're creating a game in which the player is expected to enter the name of their five favorite foods. You could always handle this type of situation as follows:
Dim FoodList FoodList = " " FoodList = FoodList & " " & InputBox("Type the name of a food that you really like.") FoodList = FoodList & " " & InputBox("Type the name of a food that you really like.") FoodList = FoodList & " " & InputBox("Type the name of a food that you really like.") FoodList = FoodList & " " & InputBox("Type the name of a food that you really like.") FoodList = FoodList & " " & InputBox("Type the name of a food that you really like.") MsgBox "You like : " & FoodList
As you can see, this example repeats the same statement over and over again in order to collect user input. Then, as proof that it did its job, it displays the data that it has collected using the MsgBox() function.
Collecting five pieces of data like this is a bit of a chore. Now imagine a situation in which you want to collect a lot more data. Instead of typing the statement over and over again, as done in the previous example, you can use the For...Next loop.
Dim Counter, FoodList FoodList = " " For Counter = 1 To 5 FoodList = FoodList & " " & InputBox("Type the name of a food that you really like.") Next MsgBox "You like : " & FoodList
Figure 6.7 demonstrates the output produced by this example.
Figure 6.7: Using a For...Next loop to collect and process user input
Take note of the fact that this new script is two lines shorter than the previous example. Unlike the previous example, other than the value of the loop's ending value, this script does not have to be modified in order to accommodate the collection of additional data. For example, to change the For...Next loop so that it can accommodate the collection of ten pieces of data, all you'd have to do is modify it like this:
For Counter = 1 To 10 FoodList = FoodList & " " & InputBox("Type the name of a food that you really like.") Next
Optionally, you can use the Exit For statement to break out of a For...Next loop at any time, like this:
Dim Counter, FoodList, NewFood FoodList = " " For Counter = 1 To 5 NewFood = InputBox("Type the name of a food that you really like.") If NewFood = "beans" Then MsgBox "Sorry, but I don't want to talk to anyone who likes beans!" Exit For End If FoodList = FoodList & " "& NewFood Next MsgBox "You like : " & FoodList
In this example, the assignment of data has been split into two different statements. The first of these statements assigns the name of the food entered by the user to a variable called NewFood. The value of NewFood is then added to the list of foods liked by the user only if it is not "beans," in which case the script displays a message and then terminates the execution of the For...Next loop. As a result, only the foods entered by the user up to the point where beans was typed are displayed.
Let's look at one last example before we continue on to examine the other loop statements supported by VBScript. In this example, the For...Next statement's optional keyword Step has been added in order to change the behavior of the loop.
Dim Counter For Counter = 1 To 9 Step 3 WScript.Echo counter Next
In this example, the script will display the value of the counter variable, which is used to control the loop's execution. Instead of counting to 9 by 1's, the script will count by 3's.
C:>CScript TextScript.vbs Microsoft (R) Windows Script Host Version 5.1 for Windows Copyright (C) Microsoft Corporation 1996–1999. All rights reserved. 1 4 7 C:>
VBScript's For Each...Next statement is a programming tool for working with all of the properties associated with objects. Every object has a number of properties associated with it. Using the For Each...Next loop, you could write a script to loop through all of an object's properties.
The syntax of the For…Each…Next statement is as follows:
For Each element In collection statements Next [element]
Element is a variable representing a property that is associated with the collection (or object). Look at the following example:
Dim FsoObject, FolderName, Member, FileList, TargtFolder Set FsoObject = CreateObject("Scripting.FileSystemObject") Set FolderName = FsoObject.GetFolder("C:Temp") For Each Member in FolderName.Files FileList = FileList & Member.name & vbCrLf Next MsgBox FileList, ," List of files in " & FolderName
This example begins by defining its variables and then establishing an instance of the FileSystemObject. It then uses the FileSystemObject object's GetFolder() method to set a reference to a folder. Next, using the folder reference, a For Each...Next loop processes all of the files (which, in this case, are considered to be properties of the folder) stored within the folder. As the For Each...Next loop executes, it builds a list of files stored within the folder and uses the vbCrLf constant to format the list in an attractive manner. The final statement displays the results, as shown in Figure 6.8.
Figure 6.8: Using a For...Each Next loop to process the contents of a folder
For Each...Next loops are also an excellent programming tool for processing the contents of arrays. For example, the following statements are all that's needed to process and display an array called GameArray, and to display each of its elements:
For Each i In GameArray Message = Message & i & vbCrLf Next WScript.Echo Message
To learn more about arrays and see a more complete example of a script that uses the For Each...Next statement, refer to the "Processing Array Contents" section in Chapter 4.
The Do...While statement creates a loop that runs as long as a specified condition is true. VBScript supports two different versions of the Do...While loop. The syntax for the first version of the Do...While loop is as follows:
Do While condition statements Loop
Condition is expressed in the form of an expression, like this:
Counter = 0 Do While Counter < 10 Counter = counter + 2 Loop
In this example, the expression (Counter < 10) allows the loop to continue as long as the value of Counter is less than 10. The value of counter is initially set to zero, but is increased by 2 every time the loop executes. As a result, the loop iterates five times.
As the While keyword has been placed at the beginning of the loop, the loop will not execute if the value of counter is already 10 or greater.
The syntax for the second format of the Do...While statement is as follows:
Do statements Loop While condition
As you can see, the While keyword had been moved from the beginning to the end of the loop. Therefore, the loop will always execute at least once, even if the condition is initially false.
Let's look at another example of the Do...While loop in action. In this example, the Do...While loop is set up to collect names and phone numbers for an address book. The loop uses the VBScript InputBox() function to collect the names and phone numbers. The names and addresses are added to a variable string and formatted such that, when displayed, each entry is listed on a separate line. The user may enter as many names and numbers as he or she wishes. When done adding address book entries, all he or she must do is type Quit as the final entry.
The script looks for a Quit entry upon every iteration of the loop.
Dim LoopCounter, AddressBook, AddressEntry LoopCounter = 0 Do While AddressEntry <> "Quit" LoopCounter = LoopCounter + 1 AddressEntry = InputBox("Please type a name, a space, and then the person's phone number", "Personal Address Book") If AddressEntry <> "Quit" Then AddressBook = AddressBook & AddressEntry & vbCrLf End If Loop MsgBox AddressBook, ,"New Address Book Entries = " & LoopCounter - 1
Figure 6.9 displays a list of four names entered as this script executed.
Figure 6.9: Using a Do...While loop to collect new address book entries
Alternatively, you could have written this example as shown next. In this example the While keyword and its associated condition have been moved to the end of the loop. However, the script still operates exactly as in the previous example.
Dim LoopCounter, AddressBook, AddressEntry LoopCounter = 0 Do LoopCounter = LoopCounter + 1 AddressEntry = InputBox("Please type a name, a space, and then the " & _ "person's phone number", "Personal Address Book") If AddressEntry <> "Quit" Then AddressBook = AddressBook & AddressEntry & vbCrLf End If Loop While AddressEntry <> "Quit" MsgBox AddressBook, ,"New Address Book Entries = " & LoopCounter -1
One of the dangers of working with loops is that you may accidentally create a loop that has no way of terminating its own execution. This is an endless loop. Endless loops run forever, needlessly consuming computer resources and degrading a computer's performance. For example, look at the following:
Counter = 0 Do While Counter < 10 Counter = Counter + 1 WScript.Echo Counter Loop
When executed, this script counts from 1 to 10. Now look at the next script.
Counter = 0 Do While Counter < 10 Counter = Counter - 1 WScript.Echo Counter Loop
It looks almost exactly like the previous example, only instead of incrementing the value of LoopCounter by 1, it increments the value of LoopCounter by -1, creating an endless loop. One way to protect against the creation of an endless loop is to put in a safety net, like this:
Counter = 0 Do While Counter < 10 Counter = Counter - 1 NoExecutions = NoExecutions + 1 WScript.Echo Counter If NoExecutions > 99 Then Exit Do End If Loop
As you can see, I added to the script a variable called NoExecutions that I then used to keep track of the number of times that loop iterated. If the loop iterates 100 times, then something is wrong. So I added an If statement to test the value of NoExecutions each time the loop is processed and to execute the Exit Do statement in the event that something goes wrong. Of course, there is no substitute for good program design and careful testing.
The VBScript Do...Until statement creates a loop that executes as long as a condition is false (that is, until it becomes true). VBScript supports two versions of the Do...Until statement. The syntax for the first version is as follows:
Do Until condition statements Loop
Let's look at an example that demonstrates how this loop works. In this example, shown next, the script prompts the player to answer a question and uses a Do...Until loop to allow the user up to three chances to correctly answer the question.
Dim MissedGuesses, PlayerAnswer MissedGuesses = 1 Do Until MissedGuesses > 3 PlayerAnswer = InputBox("Where does Peter Pan live?") If PlayerAnswer <> "Neverland" Then MissedGuesses = MissedGuesses + 1 If MissedGuesses < 4 Then MsgBox "Incorrect: You have " & 4 - MissedGuesses & "guesses left. Please try again." Else MsgBox "Sorry. You have used up all your chances." End If Else MissedGuesses = 4 MsgBox "Correct! I guess that you must believe in Faith, Trust and Pixy Dust!" End If Loop
In this example, the loop has been set up to execute until the value of a variable named MissedGuesses becomes greater than 3. The variable is initially set equal to 1 and is incremented by 1 each time the loop executes, unless the player provides a correct answer, in which case the script sets the value of MissedGuesses to 4 in order to arbitrarily terminate the loop's execution.
Figure 6.10 demonstrate the execution of this script by showing the popup dialog that appears if the player guesses incorrectly wrong on his or her first attempt to answer the question.
Figure 6.10: Using a Do...Until loop to provide the player with three chances to correctly answer a question
The syntax of the second form of the Do...Until statement is as follows:
Do statements Loop Until condition
As you can see, the Until keyword and its associated condition have been moved from the beginning to the end of the loop, thus ensuring that the loop will execute at least once.
The While...End statement creates a loop that executes as long as a tested condition is true.
The syntax for this loop is as follows:
While condition statements End
The Do...While and Do...Until loops provide the same functionality as the While...End loop. The general rule of thumb, therefore, is that you should use one of the Do loops in place of this statement. However, I'd be remiss if I failed to show you how this statement works, so take a look at the following example:
Dim TheCount, CountList TheCount = 0 While TheCount < 10 TheCount = TheCount + 1 CountList = CountList & TheCount & vbCrLf End MsgBox "This is how to count to 10:" & vbCrLf & vbCrLf & _ CountList, , "Counting Example"
This example begins by initializing two variables. TheCount is used to control the loop's execution. CountList is used to build a formatted script containing the numbers counted by the script. The loop itself iterates ten times. Figure 6.11 shows the output created by this example when run using the WScript execution host.
Figure 6.11: Counting to ten using a While...End loop
Let's turn our attention back to the Guess a Number game. In this game, the player is prompted to guess a randomly generated number between 1 and 100. Each time the player takes a guess, the script will check to see if the correct number was guessed. If not, the script will provide a hint to help the player on his or her next guess.
Through the development of this script, you will further enhance your knowledge and understanding of working with the Do...Until loop. You will also demonstrate your ability to work with the If statement, and learn how to work with a number of new built-in VBScript functions.
The basic design of the Guess a Number game is to begin by asking the player to guess a number between 1 and 100, and then to help the user guess the number by providing hints. This project will be completed in five steps. These steps are as follows:
As a kind of project bonus, once you have completed the Guess a Number game, I'll show you how to create a VBScript desktop shortcut for it. I'll also show you how to use shortcuts to configure the Windows Start Menu and Quick Launch toolbar.
Beginning the Guess a Number Game
Begin by creating a new script and adding your script template.
'************************************************************************* 'Script Name: PickANumber.vbs 'Author: Jerry Ford 'Created: 10/19/02 'Description: This script plays a number-guessing game with the user '************************************************************************* 'Initialization Section Option Explicit
Next, create a constant and assign it the text message to be used in the titlebar of the script's popup dialogs.
Const cGreetingMsg = "Pick a number between 1 - 100"
Then define four variables as shown next. UserNumber will be used to store the player's numeric guess. RandomNo will store the script's randomly generated number. OkToEnd is a variable that the script will use to determine whether the game should be stopped, and NoGuesses will be used to keep track of the number of guesses that the player makes.
Dim UserNumber, RandomNo, OkToEnd, NoGuesses
Finally, set the initial value of NoGuesses to 0, like this:
NoGuesses = 0
Generating the Game's Random Number
The following statements come next and are responsible for generating the game's random number:
'Generate a random number Randomize RandomNo = FormatNumber(Int((100 * Rnd) + 1))
The Randomize statement ensures that a random number is generated each time the game is played. The last statement uses the following built-in VBScript functions to generate a number between 1 and 100.
Creating a Loop to Control the Game
Now you'll need to set up the Do...Until loop that controls the game's execution. In this example, the loop executes until the value assigned to the OkToEnd variable is set to yes.
Do Until OkToEnd = "yes" 'Prompt users to pick a number UserNumber = InputBox("Type your guess:",cGreetingMsg) NoGuesses = NoGuesses + 1 . . . Loop
As you can see, the only statement inside the loop, for now, prompts the player to guess a number and keeps track of the number of guesses made by the player.
Testing Player Input
Now let's put together the code that performs validation of the data supplied by the player.
'See if the user provided an answer If Len(UserNumber) <> 0 Then 'Make sure that the player typed a number If IsNumeric(UserNumber) = True Then . . . Else MsgBox "Sorry. You did not enter a number. Try again.", , cGreetingMsg End If Else MsgBox "You either failed to type a value or you clicked on Cancel. " & _ "Please play again soon!", , cGreetingMsg OkToEnd = "yes" End If
The first validation test is performed using the built-in VBScript Len() function. It is used to ensure that the player actually typed in a number before clicking on the OK button. If the player's input is not zero characters long, the game continues to the next test. Otherwise, an error message is displayed, and the value of OkToEnd is set to yes, terminating the loop and ending the game. If the length test is passed, then the script performs a second validation test on the player's input. This time, the built-in VBScript IsNumeric() function is used to make sure that the player typed a number instead of a letter or other special character. If a number was typed, then the game continues. If a number was not typed, then an error message is displayed, but the game continues with the next iteration of the loop.
Determine Whether the Player's Guess Is High, Low, or Correct
There are three more sets of statements that need to be added to the script. They will be inserted one after another, just after the If statement that performs the game's second validation test.
The first of these three sets of statements is shown below. It begins by verifying that the user's guess matches the game's randomly selected number. Then it displays a message congratulating the player, showing the random number, and showing the number of guesses that it took for the player to guess it. Finally, the value of OkToEnd is set equal to yes. This will terminate the loop and allow the game to end.
'Test to see if the user's guess was correct If FormatNumber(UserNumber) = RandomNo Then MsgBox "Congratulations! You guessed it. The number was " & _ UserNumber & "." & vbCrLf & vbCrLf & "You guessed it " & _ "in " & NoGuesses & "guesses.", ,cGreetingMsg OkToEnd = "yes" End If
The second of the three sets of statements provides the player with help if his or her guess is too low. The value of OkToEnd is set equal to no. This ensures that the loop that controls the game will continue.
'Test to see if the user's guess was too low If FormatNumber(UserNumber) < RandomNo Then MsgBox "Your guess was too low. Try again", ,cGreetingMsg OkToEnd = "no" End If
Finally, the last collection of statements provides the player with help if his or her guess is too high. The value of OkToEnd is set equal to no. This ensures that the loop that controls the game will continue.
'Test to see if the user's guess was too high If FormatNumber(UserNumber) > RandomNo Then MsgBox "Your guess was too high. Try again", ,cGreetingMsg OkToEnd = "no" End If
Let's put all of the pieces of the Guess a Number script together and see how it looks fully laid out.
'************************************************************************* 'Script Name: PickANumber.vbs 'Author: Jerry Ford 'Created: 10/19/02 'Description: This script plays a number-guessing game with the user '************************************************************************* 'Initialization Section Option Explicit Const cGreetingMsg = "Pick a number between 1 - 100" Dim UserNumber, RandomNo, OkToEnd, NoGuesses NoGuesses = 0 'Main Processing Section 'Generate a random number Randomize RandomNo = FormatNumber(Int((100 * Rnd) + 1)) 'Loop until either the user guesses correctly or the user clicks on Cancel Do Until OkToEnd = "yes" 'Prompt user to pick a number UserNumber = InputBox("Type your guess:",cGreetingMsg) NoGuesses = NoGuesses + 1 'See if the user provided an answer If Len(UserNumber) <> 0 Then 'Make sure that the player typed a number If IsNumeric(UserNumber) = True Then 'Test to see if the user's guess was correct If FormatNumber(UserNumber) = RandomNo Then MsgBox "Congratulations! You guessed it. The number was " & _ UserNumber & "." & vbCrLf & vbCrLf & "You guessed it "& _ "in "& NoGuesses & " guesses.", ,cGreetingMsg OkToEnd = "yes" End If 'Test to see if the user's guess was too low If FormatNumber(UserNumber) < RandomNo Then MsgBox "Your guess was too low. Try again", ,cGreetingMsg OkToEnd = "no" End If 'Test to see if the user's guess was too high If FormatNumber(UserNumber) > RandomNo Then MsgBox "Your guess was too high. Try again", ,cGreetingMsg OkToEnd = "no" End If Else MsgBox "Sorry. You did not enter a number. Try again.", , cGreetingMsg End If Else MsgBox "You either failed to type a value or you clicked on Cancel. " & _ "Please play again soon!", , cGreetingMsg OkToEnd = "yes" End If Loop
Okay, it's time to run the script and see if it works as promised (don't worry, it will). After testing to see if the script works as expected, retest it to see if you can break it. For example, try feeding it special characters or letters instead of numbers. Once you're satisfied with the operation of the script, keep reading. I have one more little goodie for you in this chapter.
Up until now you have been running your scripts in either of two ways. One is by opening the Windows Command Console and typing in the name of a execution host, followed by the path and filename of your scripts, at the Windows Command Prompt. The other is by locating the folder in which the script resides and opening it (that is, double-clicking on it).
Windows provides shortcuts as a convenient alternative for executing Windows applications and scripts from the Windows desktop. A shortcut provides access to a Windows resource without requiring the user to find or even know the actual location of the resource that it represents. For example, just about any new application that you install on your computer will automatically add an application shortcut to the Programs menu located on the Windows Start Menu. In addition, most application installation procedures offer to add a shortcut for the application on the Windows desktop. Some application install processes go a step further and add a shortcut for the application on the Windows Quick Launch toolbar.
Definition
Shortcuts are links or pointers to Windows objects. These objects can be just about anything, including Windows applications, folders, files, printers, disk drives, and scripts.
Using VBScript and the WSH, you can create a setup script that configures shortcuts for your VBScript games in any of these locations. Of course, you can always manually create shortcuts for your scripts, but the advantage of scripting their setup is that, once written, you can re-create these shortcuts on any computer. For example, if you purchase a new computer, all you'd have to do is copy your VBScripts over from your older computer and then run your VBScript setup script, and all your shortcuts would be re-created. Likewise, if you give copies of your VBScript games to all your friends, all they'd have to do to set up shortcuts for the scripts is to run the setup script.
Definition
The Windows Quick Launch toolbar is an optional toolbar located on top of the Windows taskbar. It provides single-click access to Windows applications. Applications typically found on this toolbar include Internet Explorer, Outlook Express, and Windows Media Player.
Examining Shortcut Properties
Windows shortcuts are identified by a small black arrow in the lower-left-hand side of the icon that represents them. Shortcuts contain information, in the form of properties, about the Windows resources that they are associated with. The most important of these properties is the path and name of the Windows resources that the shortcut represents.
You can view the properties associated with any shortcut by right-clicking on the shortcut and selecting Properties. The shortcut's Properties dialog will appear. Click the Shortcut property sheet to view these properties, as shown in Figure 6.12.
Figure 6.12: Examining the properties associated with a shortcut to the Windows Notepad application
Creating Desktop Shortcuts
As you will see, you can create a desktop shortcut in just five simple steps. To demonstrate, let's create a shortcut for the GuessANumber.vbs game on the Windows desktop.
The first step in creating the game's shortcut is to establish an instance of the WshShell object. The script will need to use this object's SpecialFolders property to access the folder that represents the Windows desktop. In addition, you'll need to use the WshShell object to instantiate the WshShortcut object in order to set shortcut properties.
The following statement establishes an instance of the WshShell object:
Set WshShl = WScript.CreateObject("WScript.Shell")
The second step in creating the shortcut is to set up a reference to the folder where the shortcut is to reside. In Windows, everything, including the Windows desktop and Start Menu, is represented as a folder. Therefore, to add a shortcut to the Windows desktop, all you have to do is save the shortcut in a special folder called Desktop by specifying a value for the WshShell object's SpecialFolder property.
DesktopFolder = WshShl.SpecialFolders("Desktop")
The third step required to set up the desktop shortcut is to use the WshShell object's CreateShortcut() method to define the shortcut and instantiate the WshShortcut object.
Set NewShortcut = WshShl.CreateShortcut(DesktopFolder & "\ GuessANumber.lnk")
DesktopFolder provides a reference to the location of the Windows desktop and \GuessANumber.lnk is the name to be assigned to the shortcut.
The fourth step in creating the new shortcut is to configure properties associated with the shortcut. The WshShortcut object provides access to these properties, which are listed in Table 6.1.
Property |
Description |
---|---|
Arguments |
Sets arguments to be passed to the application or script associated with the shortcut |
Description |
Adds a comment to the shortcut |
Hotkey |
Sets a keyboard keystroke sequence that can be used to activate the application associated with the shortcut |
IconLocation |
Sets the shortcut's icon |
TargetPath |
Sets the path and filename of the object associated with the shortcut |
WindowStyle |
Sets the window style used when the application associated with the shortcut is opened (e.g. normal, minimized, or maximized) |
WorkingDirectory |
Sets the default working directory or folder for the application associated with the shortcut |
Only the TargetPath property must be set in order to create a shortcut. Configuration of the remaining shortcut properties is optional. The following statement configures the TargetPath property by setting it to C:GuessANumber.vbs:
NewShortcut.TargetPath = "C: GuessANumber.vbs"
Examples of how to set other properties are
NewShortcut.Description = "Guess a Number Game" NewShortcut.Hotkey = "CTRL+Alt+G"
The first of these two statements adds a description to the shortcut. Once created, this description can be viewed by moving the pointer over the shortcut's icon for a few moments. The second statement defines a keyboard keystroke sequence that, when executed, will active the shortcut and thus open its associated Windows resources (that is, run your script). In this case, pressing the CTRL, ALT and J keys at the same time will run the VBScript.
The fifth and final step in creating the shortcut is to save it using the WshShortcut object's Save() method, like this:
NewShortcut.Save()
Let's put all five of these statements together to complete the script.
Set WshShl = WScript.CreateObject("WScript.Shell") DesktopFolder = WshShl.SpecialFolders("Desktop") Set NewShortcut = WshShl.CreateShortcut(DesktopFolder & "\ GuessANumber.lnk") NewShortcut.TargetPath = "c:GuessANumber.vbs" NewShortcut.Save()
TRICK |
It's just as easy to delete a shortcut using VBScript and the WSH as it is to create one. For example, create and run the following script to delete the shortcut that the previous script created: Set WshShl = WScript.CreateObject("WScript.Shell") TargetFolder = WshShl.SpecialFolders("Desktop") Set FsoObject = CreateObject("Scripting.FileSystemObject") Set NewShortcut = FsoObject.GetFile(TargetFolder & "\GuessANumber.lnk") NewShortcut.Delete The first statement shown above establishes an instance of the WshShell object. The second statement uses the WshShell object's SpecialFolders property to identify the location of the shortcut. The third statement creates an instance of the VBScript FileSystemObject. The fourth statement uses the FileSystemObject object's GetFile() method to instantiate the File object and create a reference to the shortcut, and the final statement deletes the shortcut using the File object's Delete() method. |
Using Shortcuts to Add Your Script to the Windows Start Menu
Windows operating systems use folders for a number of purposes. For example, folders are used to store system files. You also use folders to store your own personal files. The Windows desktop is also a folder. Likewise, the Windows Start Menu and its many submenus (such as the Programs, Documents, and Favorites menus) are just a collection of folders. By adding and removing shortcuts to and from these folders you are able to change their contents.
In order to work with the folders that make up the Windows Start Menu, you need to create a reference to the appropriate special folder in the exact same way that you created a reference to the special desktop folder in the previous shortcut example. The name of the special folder that represents the Windows Start Menu is StartMenu. Using the following script, you can programmatically configure this menu:
Set WshShl = WScript.CreateObject("WScript.Shell") TargetFolder = WshShl.SpecialFolders("StartMenu") Set NewShortcut = WshShl.CreateShortcut(TargetFolder & "\ GuessANumber.lnk") NewShortcut.TargetPath = "c: GuessANumber.vbs" NewShortcut.Save
As you can see, other than specifying a different special folder name, this script is no different than the script that created the desktop shortcut. Create and run this script. Figure 6.13 shows the new menu entry added by this script on a computer that runs Windows XP.
Figure 6.13: Examining the Start Menu after adding a shortcut to the GuessANumber.vbs game
Using Shortcuts to Add Your Script to the Programs Menu
You can just as easily add shortcuts for your VBScripts to other menus not on the Windows Start Menu. For example, the following script adds a menu entry for the GuessANumber.vbs script on the Programs menu.
Set WshShl = WScript.CreateObject("WScript.Shell") TargetFolder = WshShl.SpecialFolders("Programs") Set NewShortcut = WshShl.CreateShortcut(TargetFolder & "\ GuessANumber.lnk") NewShortcut.TargetPath = "c: GuessANumber.vbs" NewShortcut.Save
Again, the only thing that changed in this script is the name of the special folder that represents the Programs menu. Figure 6.14 demonstrates how the Programs menu now looks with its new shortcut.
Figure 6.14: Examining the Programs Menu after adding a shortcut to the GuessANumber.vbs game
Using Shortcuts to Add Your Script to the Quick Launch Toolbar
The Windows Quick Launch toolbar is an optional toolbar located on the Windows taskbar of computers running Windows 98, Me, 2000, and XP. It provides single-click access to Windows resources. The next script demonstrates how to add a shortcut for the GuessANumber.vbs script to the Quick Launch toolbar. For the most part, this script is no different than any of the previous examples. There is one key difference, however, which I have highlighted to make it stand out.
Set WshShl = WScript.CreateObject("WScript.Shell") QuickLaunchToolbar = WshShl.SpecialFolders("AppData") AppDataPath = QuickLaunchToolbar + "MicrosoftInternet ExplorerQuick Launch" Set NewShortcut = WshShl.CreateShortcut(AppDataPath + "\GuessANumber.lnk") NewShortcut.TargetPath = "C: GuessANumber.vbs" NewShortcut.Save
What makes working with the Quick Launch toolbar different than working with other Windows special folders is that you must specify the location of the Quick Launch toolbar within the special folder (AppData) that contains it.
Figure 6.15 shows how the Quick Launch toolbar appears once the shortcut of your VBScript game has been added to it.
Figure 6.15: Examining the Windows Quick Launch toolbar after adding a shortcut to the GuessANumber.vbs game
Now let's put together some of the shortcut examples that you worked on previously to make a new script that creates shortcuts for GuessANumber.vbs on the Windows desktop, Programs menu, and Quick Launch toolbar.
'************************************************************************* 'Script Name: ShortcutMaker.vbs 'Author: Jerry Ford 'Created: 11/28/02 'Description: This script creates shortcuts for the GuessaNumber.vbs VBScript 'on the Widows desktop, Programs menu, and Quick Launch toolbar. '************************************************************************* 'Initialization Section Option Explicit Dim WshShl, TargetFolder, DesktopShortcut, ProgramsShortcut, AppDataPath Dim QuickLaunchShortcut 'Establish an instance of the WshShell object Set WshShl = WScript.CreateObject("WScript.Shell") 'Create the Desktop shortcut TargetFolder = WshShl.SpecialFolders("Desktop") Set DesktopShortcut = WshShl.CreateShortcut(TargetFolder + "\ GuessANumber.lnk") DesktopShortcut.TargetPath = "C: GuessANumber.vbs" DesktopShortcut.Description = "Guess a Number Game" DesktopShortcut.Hotkey = "CTRL+Alt+G" DesktopShortcut.Save 'Create the Programs menu shortcut TargetFolder = WshShl.SpecialFolders("Programs") Set ProgramsShortcut = WshShl.CreateShortcut(TargetFolder & "\ GuessANumber.lnk") ProgramsShortcut.TargetPath = "c: GuessANumber.vbs" ProgramsShortcut.Save 'Create the Quick Launch Toolbar shortcut TargetFolder= WshShl.SpecialFolders("AppData") AppDataPath = TargetFolder + "MicrosoftInternet ExplorerQuick Launch" Set QuickLaunchShortcut = WshShl.CreateShortcut(AppDataPath + "\ GuessANumber.lnk") QuickLaunchShortcut.TargetPath = "C: GuessANumber.vbs" QuickLaunchShortcut.Save
I was able to achieve a few economies of scale here. First of all, I only had to instantiate the WshShell object once. I also reused the TargetFolder variable over and over again. However, I thought that it made the script more readable to assign a different variable to each special folder reference. Run this script and you should see shortcuts for GuessANumber.vbs added to the Windows desktop, Programs Menu, and Quick Launch toolbar.
In this chapter you learned about loops and how to apply them to your VBScripts. You demonstrated your understanding of this fundamental programming concept through the development of the Guess a Number game. You also leaned how to programmatically work with Windows shortcuts, and how to use them to create shortcuts for your scripts, as well as how to configure a number of Windows features, including the Windows desktop, Start Menu, and Quick Launch toolbar.
Part I - Introducing the WSH and VBScript
Part II - Learning VBScript & WSH Scripting
Part III - Advanced Topics
Part IV - Appendices