230 Take a few minutes to double-check all your work and then give this game a whirl. This is a pretty big script, so you may have to fix a few syntax errors introduced by typos you may have made when keying in the script. Once everything is working correctly, you should have a really cool game to share with—and impress—all your friends! Summary In this chapter you learned how to use procedures to streamline the organization of your VBScripts, allowing you to develop larger and more complex scripts, and, of course, games. In addition, you learned how to create reusable units of code, allowing you to make your scripts smaller and easier to mange. Finally, you learned how to control variable scope by localizing variables within procedures. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition C HALLENGES 1. Give the BlackJack Lite game’s splash screen a more polished look by providing additional information in the Rules and Instructions section of the dialog. 2. Improve the BlackJack Lite game by adding logic to include the selection of the card’s suit (club, heart, spade, or diamond). 3. Once you have modified the BlackJack Lite game to assign cards that include both the card’s suit and number, add additional logic to ensure that the same card is not used twice in the same hand. 4. Add scorekeeping logic to the BlackJack Lite game, and display the number of won and lost hands at the end of each game. Part Chapter 8: Storing and Retrieving Data Chapter 9: Handling Script Errors Chapter 10: Using the Windows Registry to Configure Scripts Settings Chapter 11: Working with Built-In VBScript Objects Chapter 12: Combining Different Scripting Languages Advanced Topics III This page intentionally left blank Storing and Retrieving Data 8 CHAPTER N ow that you’ve learned the basics of VBScript programming using the WSH, its time to tackle more advanced topics. In this chapter, you’ll learn how to work with and administer Windows files and folders, including storing data in reports and creating log files. You’ll see how to open up and pro- grammatically read the contents of text files to process script input. You’ll learn how to retrieve script configuration settings stored in external files and then use this information to control the way your scripts execute. Finally, I’ll show you how to automate file and folder management by using VBScript to copy, move, and delete individual and groups of files and folders. Specifically, you will learn how to • Create and write data to text files • Open and process data stored in text files • Copy, move, and delete files and folders • Retrieve script configuration settings from external files Project Preview: The Lucky Lottery Number Picker This chapter shows you how to create the Lucky Lottery Number Picker game, which assists players by randomly generating lottery ticket numbers. The player only needs to specify how many lottery tickets he or she plans to purchase and CHAPTER 234 the game generates the appropriate amount of numbers. By default, the game assumes that it should generate six numbers for each lottery ticket the player wants to purchase. How- ever, by editing an external configuration file that stores the game’s execution settings, the player can modify the game to generate any amount of numbers per play. Figures 8.1 through 8.4 show the Lucky Lottery Number Picker in action. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 8.1 The game begins by asking the player how many different sets of lottery numbers should be generated. Figure 8.2 By default, the game displays configuration information at the top of its output followed by the lottery numbers. By the time you’ve completed this chapter and created the Lucky Lottery Number Picker game, you will have mastered the building blocks required to work with and administer Windows files and folders. By learning how to store script configuration settings in external files, you’ll also learn how to make your VBScripts easier to control and modify. Working with the Windows File System The WSH core object model provides the capability to interact with all sorts of Windows resources, such as the Windows desktop and Registry; however, it fails to provide any access to the Windows file system, so you cannot use it to access local disk drives or to work with files and folders. Instead of providing this functionality as part of the WSH core object model, Microsoft chose to implement it via the FileSystemObject, which is one of VBScript’s run-time objects. Refer to Table 3.4 in Chapter 3, “VBScript Basics” for a complete listing of VBScript’s run-time objects. 235 Chapter 8 • Storing and Retrieving Data Figure 8.3 By changing script configuration settings stored in an external configuration file, the player can tell the script to provide only summary level information. Figure 8.4 The game ends only after displaying information about its creator. 236 The FileSystemObject is VBScript’s primary run-time object. All other run-time objects, except for the Dictionary object, are derived from it. To use the FileSystemObject, you must instantiate it as shown here: Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) The first step in setting up an instance of the FileSystemObject is to use the Set statement to associate a variable with it. This is accomplished by using the WScript object’s CreateObject() method and specifying the FileSystemObject as Scripting.FileSystemObject. Once instanti- ated, you can interact with the FileSystemObject by referencing the variable that has been set up, thus providing access to all FileSystemObject properties and methods. To jump-start your understanding of the FileSystemObject and how to use it, let’s begin with an example. In this example, a VBScript is created that uses the FileSystemObject to retrieve and display the properties associated with a file named Sample.txt. The script begins by instantiating the FileSystemObject and associating it with a variable named objFso. Next, the FileSystemObject object’s GetFile() method retrieves a reference to the File object that specifically refers to Sample.txt, which is located in the computer C:\Temp folder. The main processing of the script then makes a series of procedure calls. The CreateDisplay String() function uses several File object properties to collect information about the Sample.txt file. The next two functions display the information that has been collected about the file and then terminate the script’s execution. ‘************************************************************************* ‘Script Name: ExtractFileProperties.vbs ‘Author: Jerry Ford ‘Created: 11/10/04 ‘Description: This script demonstrates how to retrieve information about ‘ a file. ‘************************************************************************* ‘Initialization Section Option Explicit On Error Resume Next Dim objFso, strInputFile, strDisplayString Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) Set strInputFile = objFso.GetFile(“C:\Temp\Sample.txt”) ‘Main Processing Section CreateDisplayString() DisplayMessage() TerminateScript() ‘Procedure Section Function CreateDisplayString() strDisplayString = “C:\Temp\Sample.txt” & vbCrLf & _ vbCrLf & “Created on: “ & vbTab & strInputFile.DateCreated & _ vbCrLf & “Last Modified: “ & vbTab & strInputFile.DateLastModified & _ vbCrLf & “Last Accessed: “ & vbTab & strInputFile.DateLastAccessed & _ vbCrLf End Function Function DisplayMessage() MsgBox strDisplayString End Function Function TerminateScript() 237 Chapter 8 • Storing and Retrieving Data 238 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition ‘Stop the execution of this script WScript.Quit() End Function The main thing to take away from this example is that it interacts with the Windows file system using properties belonging to the File object to collect information about a given file. To work with the File object, you have to use the FileSystemObject object’s GetFile() method, which first requires that you set up an instance of the FileSystemObject. If you run this script, you’ll see output similar to that shown in Figure 8.5. Opening and Closing Files Now that you know how to instantiate the FileSystemObject within your VBScripts and have seen an example of how to use it to reference other run-time objects and their associated properties, you are ready to start learning how to work with files and folders. Before you open a file or create a new file, you must determine whether or not the file already exists. You can do this using the FileSystemObject object’s FileExists() method as demonstrated here: If (objFso.FileExists(“C:\Temp\Sample.txt”)) Then . . . End If To begin working with a file, you must open it. This is done using the FileSystemObject object’s OpenTextFile() method, which requires that you provide the following pieces of information: • Name and path of the file • How to open the file • Whether to create a new file if the file does not already exist Figure 8.5 Using FileSystem Object properties to retrieve information about a file. Table 8.1 defines constants and the values you will use to tell the OpenTextFile() method how to open the file. Table 8.2 outlines the two available options that determine what the OpenTextFile() method should do if the file does not already exist. You must be careful to always specify the appropriate constant value when telling the OpenTextFile() method how to open a file. For example, if you accidentally open a file in ForWriting mode when you actually meant to append to the end of the file, then you will overwrite the contents already stored in the file. Let’s look at a VBScript that puts what you have just learned into action. In this example, the script opens a file named Sample.txt, which resides in the Temp directory on the com- puter’s C: drive. If the file exists, the script opens it. If the file doesn’t already exist, the script creates it. Once opened, the script writes a few lines of text and then closes the file. ‘************************************************************************* ‘Script Name: FileCreate.vbs ‘Author: Jerry Ford ‘Created: 11/10/04 239 Chapter 8 • Storing and Retrieving Data Constant Description Value ForReading Opens a file in preparation for reading 1 ForWriting Opens a file in preparation for writing 2 ForAppending Opens a file allowing text to be written to the end of the file 8 TABLE 8.1 OPENT EXTFILE() CONSTANTS Value Description True Open a file if it already exists; create and open a new file if it does not already exist False Open a file if it already exists; otherwise, take no additional action TABLE 8.2 OPENT EXTFILE() FILE C REATION O PTIONS . 8 • Storing and Retrieving Data 238 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition ‘Stop the execution of this script WScript.Quit() End Function The main thing. procedures. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition C HALLENGES 1. Give the BlackJack Lite game’s splash screen a more polished look by providing additional information. Lottery Number Picker in action. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 8.1 The game begins by asking the player how many different sets of lottery