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.. Specifically, you will learn h
Trang 1Take 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
CH A L L E N G E S
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.
Trang 2Retrieving Data
Registry to Configure Scripts Settings
VBScript Objects
Scripting Languages
Advanced Topics
III
Trang 3This page intentionally left blank
Trang 4Storing and Retrieving Data
8
C H A P T E R
Now 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
C H A P T E R
Trang 5the 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.
Trang 6By 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.
Trang 7The FileSystemObject is VBScript’s primary run-time object All other run-time objects, except for the Dictionaryobject, 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 FileSystemObjectis to use the Setstatement to associate a variable with it This is accomplished by using the WScriptobject’s CreateObject()
method and specifying the FileSystemObjectas Scripting.FileSystemObject Once instanti-ated, you can interact with the FileSystemObjectby referencing the variable that has been set up, thus providing access to all FileSystemObjectproperties and methods
To jump-start your understanding of the FileSystemObjectand how to use it, let’s begin with
an example In this example, a VBScript is created that uses the FileSystemObjectto retrieve and display the properties associated with a file named Sample.txt The script begins by instantiating the FileSystemObjectand associating it with a variable named objFso Next, the FileSystemObjectobject’s GetFile()method retrieves a reference to the Fileobject 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 Fileobject 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
Trang 8Set 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
Trang 9238 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 Fileobject to collect information about a given file To work with the Fileobject, 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 FileSystemObjectwithin 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 FileSystemObjectobject’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.
Trang 10Table 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
ForWritingmode 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 Tempdirectory 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
TA B L E 8 1 OP E NTE X TFI L E( ) CO N S T A N T S
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
TA B L E 8 2 OP E NTE X TFI L E( ) FI L E CR E A T I O N OP T I O N S