1. Trang chủ
  2. » Công Nghệ Thông Tin

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

10 351 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 172,63 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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,” y

Trang 1

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 statecom-ment 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 comdocu-ments 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!”

Figure 3.7

The error

message caused

by an unmatched

quotation mark in

a MsgBox()

statement

Trang 2

And EndIf LSet RSet

Currency If Optional True

Dim Implements ParamArray TypeOf

Double Integer Private Variant

Else Let RaiseEvent While

TA B L E 3 2 V B SC R I P TS CO L L E C T I O N O F RE S E R V E D WO R D S

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.

H I N T

Trang 3

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

Trang 4

The rest of the template is divided into three sections.

• Initialization Section Contains statements that globally affect the scripts, including

Option Explicitand 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.

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 Matchobjects

RegExp Supports regular expressions

SubMatches Collection Provides scripts with access to read-only values of regular expression

submatch strings

TA B L E 3 3 V B SC R I P T BU I LT-I N OB J E C T S

Trang 5

Working with VBScript Run-Time Objects

In addition to its core object model, VBScript’s FileSystemObjectobject 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 FileSystemObjectobject 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

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

TA B L E 3 4 V B SC R I P T RU N- TI M E OB J E C T S

Trang 6

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

TA B L E 3 4 V B SC R I P T RU N- TI M E OB J E C T S (C O N T I N U E D)

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 trueor falsebased on whether the file pointer

has reached the TextStreamfile’s end-of-line marker

AtEndOfStream Returns a value of either trueor falsebased on whether the end of a

TextStreamfile has been reached

Attributes Modifies or retrieves file and folder attributes

AvailableSpace Retrieves the amount of free space available on the specified drive

TA B L E 3 5 V B SC R I P T RU N- TI M E PR O P E R T I E S

(continues)

Trang 7

Property Name Description

Column Retrieves the current column position in a TextStreamfile

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

Dictionaryobject

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 Drivescollection representing all the drives found on the

computer

DriveType Returns a value identifying a drive’s type

Files Establishes a Filescollection to represent all the Fileobjects 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 trueor falsebased on the availability of the

specified drive

IsRootFolder Returns a value of either trueor falsebased on whether the specified

folder is the root folder

Item Retrieves or sets an item based on the specified Dictionaryobject key

Key Sets a Dictionaryobject key

Line Retrieves the current line number in the TextStreamfile

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 Folderobject 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

TA B L E 3 5 V B SC R I P T RU N- TI M E PR O P E R T I E S (C O N T I N U E D)

Trang 8

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.

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 Folderscollection 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

TA B L E 3 5 V B SC R I P T RU N- TI M E PR O P E R T I E S (C O N T I N U E D)

Method Name Description

Add (Dictionary) Adds a key and item pair to a Dictionaryobject

Add (Folders) Adds a Folderto a collection

BuildPath Appends a name to the path

Close Closes an open TextStreamfile

CopyFile Copies one or more files

CopyFolder Recursively copies a folder

CreateFolder Creates a new folder

CreateTextFile Creates a file and a TextStreamobject so that it can be read from and

written to

Delete Deletes a file or folder

DeleteFile Deletes a file

TA B L E 3 6 V B SC R I P T RU N- TI M E ME T H O D S

(continues)

Trang 9

Method Name Description

DeleteFolder Deletes a folder’s contents

DriveExists Returns a value of trueor falsebased on whether a drive exists

Exists Returns a value of trueor falsebased on whether a key exists in a

Dictionaryobject

FileExists Returns a value of trueor falsebased on whether the specified file can

be found

FolderExists Returns a value of trueor falsebased 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 Driveobject associated with the drive in the specified path

GetDriveName Returns the name of a drive

GetExtensionName Returns a file’s extension

GetFile Returns a Fileobject

GetFileName Returns the last file name or folder of the specified path

GetFileVersion Returns a file’s version number

GetFolder Returns the Folderobject 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 Dictionaryobject are stored

Keys Returns an array containing the keys in a Dictionaryobject

MoveFile Moves one or more files

MoveFolder Moves one or more folders

OpenAsTextStream Opens a file and retrieves a TextStreamobject to provide a reference to

the file

OpenTextFile Opens a file and retrieves a TextStreamobject to provide a reference to

the file

Read Returns a string containing a specified number of characters from a

TextStreamfile

TA B L E 3 6 V B SC R I P T RU N- TI M E ME T H O D S (C O N T I N U E D)

Trang 10

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

Method Name Description

ReadAll Reads the entire TextStreamfile and its contents

ReadLine Reads an entire line from the TextStreamfile

Remove Deletes a Dictionaryobject’s key, item pair

RemoveAll Deletes all Dictionaryobject’s key, item pairs

Skip Skips a specified number of character positions when processing a

TextStreamfile

SkipLine Skips an entire line when processing a TextStreamfile

Write Places a specified string in the TextStreamfile

WriteBlankLines Writes a specified number of newlinecharacters to the TextStreamfile

WriteLine Writes the specified string to the TextStreamfile

TA B L E 3 6 V B SC R I P T RU N- TI M E ME T H O D S (C O N T I N U E D)

Ngày đăng: 03/07/2014, 18:20

TỪ KHÓA LIÊN QUAN