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

Microsoft WSH and VBScript Programming for the Absolute Beginner Part 10 ppsx

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 (172.63 KB, 10 trang )

70
Unfortunately, the statement’s syntax requirements have not been followed. The MsgBox()
function requires that all text messages be enclosed within a pair of quotation marks. If you
look closely, you will see that the closing quotation mark is omitted. Figure 3.7 shows the
error produced by this statement at run-time.
Reserved Characters
Like any programming language, VBScript has a collection of reserved words. Reserved words
are words that you cannot use within your scripts because VBScript also assigns a special
meaning to them. Some of these words are reserved because they are part of the language
itself, and others are reserved for future use. Table 3.2 lists VBScript’s reserved words. The
important thing to remember when it comes to VBScript reserved words is that you can only
use them as intended (that is, you cannot use them as variables, constants, and procedure
names).
Adding Comments
One of the easiest VBScript statements to understand is the comment statement. The com-
ment statement gives you the ability to add to your VBScripts descriptive text that docu-
ments why you wrote the script the way you did. Documenting your scripts with comments
makes them easier to support and helps others who may come after you to pick up where
you left off. Comments do not have any affect on the execution of your scripts and you
should use them liberally.
Comments can be added to scripts using the VBScript
Rem (short for remark) statement, as
follows:
Rem Use the VBScript MsgBox() function to display a message
MsgBox “Thanks for playing!”
Comments also can be created using the ‘ character:
‘ Use the VBScript MsgBox() function to display a message
MsgBox “Thanks for playing!”
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 3.7
The error


message caused
by an unmatched
quotation mark in
a MsgBox()
statement.
71
Chapter 3 • VBScript Basics
And EndIf LSet RSet
As Enum Me Select
Boolean Eqv Mod Set
ByRef Event New Shared
Byte Exit Next Single
ByVal False Not Static
Call For Nothing Stop
Case Function Null Sub
Class Get On Then
Const GoTo Option To
Currency If Optional True
Debug Imp Or Type
Dim Implements ParamArray TypeOf
Do In Preserve Until
Double Integer Private Variant
Each Is Public Wend
Else Let RaiseEvent While
ElseIf Like ReDim With
Empty Long Rem Xor
End Loop Resume
TABLE 3.2 VBSCRIPT’ S C OLLECTION OF R ESERVED W ORDS
The ‘ character is my preferred style. I find it less visually intrusive and just as effective.
Also, you can add a comment to the end of any statement:

MsgBox “Thank you for playing” ‘Display a thank you message
One sign of an experienced programmer is the amount of and usefulness of
comments added to his or her scripts. Consider adding comments that describe
the function of variables, constants, and arrays; also use them to explain com-
plicated pieces of coding.
HINT
72
Comments also can be used to create a script template, which will provide additional struc-
ture to your VBScripts. For example, consider the following template:
‘*************************************************************************
‘Script Name: ScriptName.vbs
‘Author: Author Name
‘Created: MM/DD/YY
‘Description: Xxxxxxxxxxxxxxxxxxxxxxxxx.
‘*************************************************************************
‘Initialization Section
Option Explicit
On Error Resume Next
Dim…
Const…
Set…
‘Main Processing Section
‘Procedure Section
‘This function
Function Xxxxx(Zzzz)
Xxxxxxxxxx
End Function
This template begins with a documentation section that provides a place to record the
script’s name, its author, its creation date, and a brief description. Other information that
you might want to add here includes

• Instructions for running the script
• Documentation for any arguments the script expects to receive at execution time
• Documentation of the recent updates to the script, including when, by whom,
and why
• Copyright information
• Contact or support information
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
The rest of the template is divided into three sections.

Initialization Section.
Contains statements that globally affect the scripts, including
Option Explicit and On Error, as well as the declaration of any variables, constants,
arrays, and objects used by the script.

Main Processing Section.
This section contains the statements that control the main
processing logic of the script. The statements in this section access the resources
defined in the Initialization Section as necessary, and call on the procedures and
functions located in the Procedure Section.

Procedure Section.
This section contains all the script’s procedures. Procedures are
groups of statements that can be called and executed as a unit. You’ll learn how to
work with procedures in Chapter 7, “Using Procedures to Organize Scripts.”
Mastering the VBScript Object Model
In Chapter 2, “Overview of the Windows Script Host,” you learned about the WSH core object
model and its properties and methods. You also learned how to instantiate WSH objects to
access and manipulate their properties and methods. VBScript also provides two collections
of objects that you can use in your scripts. Table 3.3 provides an overview of VBScript’s built-in
or core objects.

Check out Chapter 11 “Working with Built-in VBScript Objects” to learn more about VBScript’s
built-in objects.
73
Chapter 3 • VBScript Basics
Object Name Description
Class Provides scripts with access to class events
Err Provides scripts with access to information about run-time errors
Match Provides scripts with access to the read-only properties of a regular
expression match
Matches Collection A collection of regular expression Match objects
RegExp Supports regular expressions
SubMatches Collection Provides scripts with access to read-only values of regular expression
submatch strings
TABLE 3.3 VBSCRIPT BUILT- IN O BJECTS
74
Working with VBScript Run-Time Objects
In addition to its core object model, VBScript’s FileSystemObject object also provides a number
of run-time objects. As Table 3.4 shows, your scripts can use these objects and their proper-
ties and methods to interface with the Windows file system.
The WSH core object model provides access to a number of Windows resources. Absent from
this model is a file system object. Therefore, to access system files from your VBScripts,
you’ll need to learn how to work with VBScript’s
FileSystemObject object. With this object,
your scripts will be able to
• Check for the existence of files and folders before attempting to work with them
• Create and delete files and folders
• Open and read files
• Write or append to files
• Close files
• Copy and move files and folders

Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Object Name Description
Dictionary Stores data key, item pairs.
Properties:
Count, Item, Key.
Methods:
Add, Exists, Items, Keys, Remove, RemoveAll.
Drive Provides script with access to disk properties.
Properties:
AvailableSpace, DriveLetter, DriveType, FileSystem, FreeSpace,
IsReady, Path, RootFolder, SerialNumber, ShareName, TotalSize, VolumeName.
Methods: This object does not support any methods.
Drives Collection Provides script with access to information regarding a drive’s location.
Properties:
Count, Item.
Methods: This object does not support any methods.
File Provides script with access to file properties.
Properties:
Attributes, DateCreated, DateLastAccessed, DateLastModified,
Drive, Name, ParentFolder, Path, ShortName, ShortPath, Size, Type.
Methods:
Copy, Delete, Move, OpenAsTextStream.
TABLE 3.4 VBSCRIPT RUN-TIME O BJECTS
75
Chapter 3 • VBScript Basics
Object Name Description
Files Collection Provides scripts with access to files stored in a specified folder.
Properties:
Count, Item.
Methods: This object does not support any methods.

FileSystemObject Provides scripts with access to the file system.
Properties:
Drives.
Methods:
BuildPath, CopyFile, CopyFolder, CreateFolder, CreateTextFile,
DeleteFile, DeleteFolder, DriveExists, FileExists, FolderExists,
GetAbsolutePathName, GetBaseName, GetDrive, GetDriveName,
GetExtensionName, GetFile, GetFileName, GetFolder, GetParentFolderName,
GetSpecialFolder, GetTempName, MoveFile, MoveFolder, OpenTextFile.
Folder Provides scripts with access to folder properties.
Properties:
Attributes, DateCreated, DateLastAccessed, DateLastModified,
Drive,
Files, IsRootFolder, Name, ParentFolder, Path, ShortName, ShortPath,
Size, SubFolders, Type.
Methods:
Copy, Delete, Move, OpenAsTextStream.
Folders Collection Provides scripts with access to folders located within another folder.
Properties:
Count, Item.
Methods:
Add.
TABLE 3.4 VBSCRIPT RUN-TIME O BJECTS ( CONTINUED)
Properties
Like WSH objects, the VBScript run-time objects support a large number of properties. Table
3.5 provides a complete list of VBScript run-time properties.
Property Name Description
AtEndOfLine Returns a value of either true or false based on whether the file pointer
has reached the
TextStream file’s end-of-line marker

AtEndOfStream Returns a value of either true or false based on whether the end of a
TextStream file has been reached
Attributes Modifies or retrieves file and folder attributes
AvailableSpace Retrieves the amount of free space available on the specified drive
TABLE 3.5 VBSCRIPT RUN-TIME P ROPERTIES
(continues)
76
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Property Name Description
Column Retrieves the current column position in a TextStream file
CompareMode Sets or returns the comparison mode used to compare a Dictionary
object’s string keys
Count Returns a value representing the number of the items in a collection or
Dictionary object
DateCreated Retrieves a file or folder’s creation date and time
DateLastAccessed Retrieves the date and time that a file or folder was last accessed
DateLastModified Retrieves the date and time that a file or folder was last modified
Drive Retrieves the drive letter where a file or folder is stored
DriveLetter Retrieves the specified drive’s drive letter
Drives Establishes a Drives collection representing all the drives found on the
computer
DriveType Returns a value identifying a drive’s type
Files Establishes a Files collection to represent all the File objects located
within a specified folder
FileSystem Retrieves the name of the file system used on the specified drive
FreeSpace Retrieves the amount of free space available on the specified drive
IsReady Returns a value of either true or false based on the availability of the
specified drive
IsRootFolder Returns a value of either true or false based on whether the specified
folder is the root folder

Item Retrieves or sets an item based on the specified Dictionary object key
Key Sets a Dictionary object key
Line Retrieves the current line number in the TextStream file
Name Gets or modifies a file or folder’s name
ParentFolder Returns a reference to the specified file or folder’s parent folder object
Path Retrieves the path associated with the specified file, folder, or drive
RootFolder Retrieves the Folder object associated with the root folder on the
specified drive
SerialNumber Retrieves the specified disk volume’s serial number
ShareName Retrieves the specified network drive’s share name
ShortName Retrieves the specified file or folder’s 8.3-character short name
TABLE 3.5 VBSCRIPT RUN-TIME P ROPERTIES (CONTINUED)
Methods
VBScript run-time objects also support a larger number of methods, which you will find essen-
tial when working with the Windows file system. These methods are outlined in Table 3.6.
77
Chapter 3 • VBScript Basics
Property Name Description
ShortPath Retrieves a file or folder’s short pathname associated with a file or folder’s
8.3-character name
Size Returns the number of bytes that make up a file or folder
SubFolders Establishes a Folders collection made up of the folders located within
a specified folder
TotalSize Retrieves a value representing the total number of bytes available on
a drive
Type Retrieves information about the specified file or folder’s type
VolumeName Gets or modifies a drive’s volume name
TABLE 3.5 VBSCRIPT RUN-TIME P ROPERTIES (CONTINUED)
Method Name Description
Add (Dictionary) Adds a key and item pair to a Dictionary object

Add (Folders) Adds a Folder to a collection
BuildPath Appends a name to the path
Close Closes an open TextStream file
Copy Copies a file or folder
CopyFile Copies one or more files
CopyFolder Recursively copies a folder
CreateFolder Creates a new folder
CreateTextFile Creates a file and a TextStream object so that it can be read from and
written to
Delete Deletes a file or folder
DeleteFile Deletes a file
TABLE 3.6 VBSCRIPT RUN-TIME M ETHODS
(continues)
78
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Method Name Description
DeleteFolder Deletes a folder’s contents
DriveExists Returns a value of true or false based on whether a drive exists
Exists Returns a value of true or false based on whether a key exists in a
Dictionary object
FileExists Returns a value of true or false based on whether the specified file can
be found
FolderExists Returns a value of true or false based on whether the specified folder
can be found
GetAbsolutePathName Retrieves a complete pathname
GetBaseName Retrieves a file name without its file extension
GetDrive Returns the Drive object associated with the drive in the specified path
GetDriveName Returns the name of a drive
GetExtensionName Returns a file’s extension
GetFile Returns a File object

GetFileName Returns the last file name or folder of the specified path
GetFileVersion Returns a file’s version number
GetFolder Returns the Folder object associated with the folder in the specified path
GetParentFolderName Returns the name of the parent folder
GetSpecialFolder Returns a special folder’s name
GetTempName Returns the name of a temporary file or folder
Items Returns an array where items in a Dictionary object are stored
Keys Returns an array containing the keys in a Dictionary object
Move Moves a file or folder
MoveFile Moves one or more files
MoveFolder Moves one or more folders
OpenAsTextStream Opens a file and retrieves a TextStream object to provide a reference to
the file
OpenTextFile Opens a file and retrieves a TextStream object to provide a reference to
the file
Read Returns a string containing a specified number of characters from a
TextStream file
TABLE 3.6 VBSCRIPT RUN-TIME M ETHODS ( CONTINUED)
Using VBScript Run-Time Objects in Your Scripts
Now seems like a good time to look at an example of how to incorporate the VBScript
FileSystemObject into your scripts and use its properties and methods to work with the
Windows file system. Take a look at the following script:
‘*************************************************************************
‘Script Name: FreeSpace.vbs
‘Author: Jerry Ford
‘Created: 11/22/02
‘Description: This script demonstrates how to use VBScript run-time
‘objects and their properties and methods.
‘*************************************************************************
‘Initialization Section

Option Explicit
Dim FsoObject, DiskDrive, AvailSpace
79
Chapter 3 • VBScript Basics
Method Name Description
ReadAll Reads the entire TextStream file and its contents
ReadLine Reads an entire line from the TextStream file
Remove Deletes a Dictionary object’s key, item pair
RemoveAll Deletes all Dictionary object’s key, item pairs
Skip Skips a specified number of character positions when processing a
TextStream file
SkipLine Skips an entire line when processing a TextStream file
Write Places a specified string in the TextStream file
WriteBlankLines Writes a specified number of newline characters to the TextStream file
WriteLine Writes the specified string to the TextStream file
TABLE 3.6 VBSCRIPT RUN-TIME M ETHODS ( CONTINUED)

×