• No results found

Windows & .NET Magazine's Guide to Automating Administrative Tasks with VBScript

N/A
N/A
Protected

Academic year: 2021

Share "Windows & .NET Magazine's Guide to Automating Administrative Tasks with VBScript"

Copied!
19
0
0

Loading.... (view fulltext now)

Full text

(1)

 Automating

 Automating

 Administrative

 Administrative

Tasks

Tasks

 with

 with

 VBScript

 VBScript

Don Baker

Don Baker, Don Jones, Lar

, Don Jones, Lary Lai, Dick Lewis,

y Lai, Dick Lewis,

Mike Otey, John Savill, Bob Wells

Mike Otey, John Savill, Bob Wells

Guide to

Guide to

(2)

A Division of Penton Media A Division of Penton Media

Windows & .NET Magazine’s Guide

Windows & .NET Magazine’s Guide

to Automating Administrative Tasks

to Automating Administrative Tasks

with VBScript

with VBScript

 By Don Baker, Don Jones, Larry Lai,

 By Don Baker, Don Jones, Larry Lai,

 Mike Otey, John Savill, Bob Wells

 Mike Otey, John Savill, Bob Wells

(3)

Copyright 2002 Copyright 2002

Windows & .NET Magazine Windows & .NET Magazine

All rights reserved. No part of this book may be reproduced in All rights reserved. No part of this book may be reproduced in any form by an electronic or mechanical means (including any form by an electronic or mechanical means (including photocopying, recording, or information storage and retrieval) photocopying, recording, or information storage and retrieval) without permission in writing from the publisher.

without permission in writing from the publisher.

It is the reader’s responsibility to ensure procedures and It is the reader’s responsibility to ensure procedures and techniques used from this book are accurate and appropriate techniques used from this book are accurate and appropriate for the user’s installation. No warranty is implied or expressed. for the user’s installation. No warranty is implied or expressed.

(4)

About the Authors

About the Authors

Don

Don BBakeraker (db(dbakeaker@[email protected]) isis.com) is a consulting engineer with Internosis, an e-business consul-s a consulting engineer with Internosis, an e-business consul-tancy in Arlington, Virginia. He is an MCSE and an MCP and specializes in Systems Management tancy in Arlington, Virginia. He is an MCSE and an MCP and specializes in Systems Management Server and automated software deployment.

Server and automated software deployment.

Don

Don JJonon eses (http://www.braincore.net)(http://www.braincore.net) is a founding partner of BrainCore.Net. He is the author of is a founding partner of BrainCore.Net. He is the author of 

 Application Center 2000 Configuration and Administration

 Application Center 2000 Configuration and Administration (Hungry Minds).(Hungry Minds).

Michael Otey

Michael Otey ([email protected]) is senior technical editor for Windows & .NET Magazine and([email protected]) is senior technical editor for Windows & .NET Magazine and president of TECA, a software-development and consulting company in Portland, Oregon. He is president of TECA, a software-development and consulting company in Portland, Oregon. He is coauthor of SQL Server 2000 Developer’s Guide

coauthor of SQL Server 2000 Developer’s Guide (Osborne/McGraw-Hill).(Osborne/McGraw-Hill).

John Savill

John Savill ([email protected]) is a qualified consultant in England and an MCSE. He is the([email protected]) is a qualified consultant in England and an MCSE. He is the author

author of The Windows NT and Windows 2000 Answer Book of The Windows NT and Windows 2000 Answer Book (Addison Wesley).(Addison Wesley).

Bob Wells

Bob Wells (bo(bobwbwells@[email protected]) m) iis a contributing editor fors a contributing editor for Windows & .NET Magazine.Windows & .NET Magazine.HeHe is a programming writer at Microsoft, where he is contributing to a new

is a programming writer at Microsoft, where he is contributing to a new SSysteystem m AdmAdm inistrationinistration Scripting Guide

(5)

Table of Contents

Table of Contents

Ch

Chap

apter 1: S

ter 1: Scriptin

cripting

g 101: D

101: Dec

eclaring

laring an

and Initializ

d Initializing

ing Va

Variable

riables

s . . .

. . .

. . . . . .

. . .

. . . .. 1

1

V

VBSBScript Basicript Basics cs . . . .. . . 11 Declaration a

Declaration and nd InitiInitializializing ng . . . .. . . 44 V

VBSBScript Directicript Directives ves . . . .. . . 44 V

VBSBScript Vcript Variables ariables . . . . . . . . . . . . .. . . 66 V

Variable Initialariable Initializatiization on . . . .. . . 66 C

Cononstant Definitistant Definitionons s . . . .. . . 66 Demo.vbs End

Demo.vbs End . . . .. . . 77

Ch

Chap

apter 2: S

ter 2: Scriptin

cripting

g 101: Workin

101: Working

g with O

with Obje

bjects

cts . . . .

. . .

. . .

. . .

. . .

. . . .

. . . 9

9

Ob

Objjects ects . . . .. . . 99 Ob

Objjects vs. Utiects vs. Utililities . . . ties . . . . . . . . . . . . .. . . 99 What Is an Ob

What Is an Ob jject? . . . ect? . . . .. . . 1111 C

Creating Oreating Objects . . . bjects . . . . . . . . . . . . .. . . 1111 C

CreateOreateO bject bject . . . .. 1212 GetOb

GetOb jject ect . . . .. . . 1414

Ch

Chap

apter 3:

ter 3: VB

VBS

Scrip

cript T

t Tec

ech

hniq

niqu

ues

es . . . .

. . .

. . .

. . .

. . .

. . .

. . .

. . . .

. . . . 17

17

Ch

Chap

apter 4: S

ter 4: Scriptin

cripting

g Co

Comm

mman

and-L

d-Line S

ine Swit

witch

ches

es . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . 21

21

A

Adddding Fling Flexibiliexibility with Sty with Switchewitches s . . . .. 2121 Hand

Hand liling Ong Omitted Switmitted Switcheches s . . . .. . . 2323

Ch

Chap

apter 5: A

ter 5: Add

dding

ing U

Us

sers

ers in B

in Bulk

ulk . . . .

. . .

. . .

. . . . . . .

. . .

. . .

. . .

. . . . . . .

. . . . 25

25

Getting S

Getting Started tarted . . . .. . . 2525 Wri

Writing the ting the SScript cript . . . . . . . . . . . . .. . . 2727 The Work Begins

The Work Begins . . . .. 2929 Do It with a Scri

Do It with a Script pt . . . .. 3131

Cha

Chapter 6

pter 6: VBS

: VBScri

cript t

pt to Generate a L

o Generate a Lis

ist of U

t of Us

ser La

er Las

st Log

t Logon T

on Times

imes for a D

for a Domain

omain . . .. 33

33

Ch

Chap

apter 7: VBS

ter 7: VBScript to D

cript to Datas

atastamp

tamp L

Log

og F

Fil

iles

es . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . .

. . 35

35

Ch

Chap

apter 8: S

ter 8: Simp

implify Wi

lify Win2K

n2K D

Des

eskto

ktop Deplo

p Deploym

ymen

ent

t . . .

. . .

. . . . . .

. . .

. . . . . .

. . .

. . .

. . . .. 37

37

The De

The Deploymeployme nt Envint Environmronmenent t . . . .. . 3737 C

Create reate a Hard Disk Image a Hard Disk Image . . . .. . . 3737 Wri

Write a FinalSte a FinalSetupetup .vbs S.vbs Script cript . . . .. . . 3838 Prepare the

Prepare the DisDisk Image k Image . . . .. . . 4242 Unattend

Unattend ed ed . . . .. 4343 GuiU

GuiUnattendenattended d . . . .. . . 4343 GuiR

GuiRununOnOnce ce . . . .. . . 4444 UserData

UserData . . . .. . . 4444 Iden

Identiftificatiication on . . . .. . . 4444 Networking

Networking . . . .. 4444 C

Clone lone the Master Image to a the Master Image to a Workstation Workstation . . . .. . . 4545

iv

iv

(6)
(7)

1

1

Chapter 1

Chapter 1

Scripting 101:

Scripting 101:

Declaring and Initializing Variables

Declaring and Initializing Variables

By Bob Wells 

By Bob Wells 

The structure of a script consists of three sections: declarations and initializations, the body of the The structure of a script consists of three sections: declarations and initializations, the body of the script, and function and subroutine definitions. In this chapter, I examine the declaration and script, and function and subroutine definitions. In this chapter, I examine the declaration and ini-tialization section in detail. Before we start, you need to know some VBScript basics to ease your tialization section in detail. Before we start, you need to know some VBScript basics to ease your transition to Windows Script Host (WSH).

transition to Windows Script Host (WSH).

VBScript Basics

VBScript Basics

As with any other programming or scripting language, VBScript has some general ground rules As with any other programming or scripting language, VBScript has some general ground rules that apply to every script. At first glance, these rules might not appear to be significant, but that apply to every script. At first glance, these rules might not appear to be significant, but

knowing these language tidbits can often shave a few minutes off a frustrating debugging exercise. knowing these language tidbits can often shave a few minutes off a frustrating debugging exercise.

The first ground rule is that VBScript isn’t case-sensitive. For example, declaring a variable as The first ground rule is that VBScript isn’t case-sensitive. For example, declaring a variable as strTempFile and later referencing it as STRtEMPfILE is perfectly legal. Likewise, VBScript statements, strTempFile and later referencing it as STRtEMPfILE is perfectly legal. Likewise, VBScript statements, function names, and subroutine names are case-insensitive. Despite this flexibility, I encourage you function names, and subroutine names are case-insensitive. Despite this flexibility, I encourage you to pick a case variation that suits your needs and stick with it.

to pick a case variation that suits your needs and stick with it.

Although VBScript is case-insensitive, some situations (e.g., comparing two string values) Although VBScript is case-insensitive, some situations (e.g., comparing two string values)

require you to be case-conscious. You also need to be case-conscious when you use Active require you to be case-conscious. You also need to be case-conscious when you use Active Direc-tory Service Interfaces (ADSI) namespace identifiers (e.g., LDAP to specify Lightweight DirecDirec-tory tory Service Interfaces (ADSI) namespace identifiers (e.g., LDAP to specify Lightweight Directory Access Protocol, WinNT to specify Windows NT, NDS to specify NetWare 4.x, NWCOMPAT to Access Protocol, WinNT to specify Windows NT, NDS to specify NetWare 4.x, NWCOMPAT to specify NetWare 3.x). You must key ADSI namespace identifiers according to the ADSI specify NetWare 3.x). You must key ADSI namespace identifiers according to the ADSI specifica-tion, or a runtime error will occur when your script attempts to bind to an ADSI namespace. (For tion, or a runtime error will occur when your script attempts to bind to an ADSI namespace. (For more information about ADSI namespace usage, read the Active Directory Programmer’s Guide more information about ADSI namespace usage, read the Active Directory Programmer’s Guide available at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netdir/ad/ 

available at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netdir/ad/  using_active_directory.asp.

using_active_directory.asp.

The second VBScript rule is that you can use either an apostrophe (‘) or a Rem statement to The second VBScript rule is that you can use either an apostrophe (‘) or a Rem statement to include comments in a script. I use both styles in Listing 1’s demo.vbs script. You can insert include comments in a script. I use both styles in Listing 1’s demo.vbs script. You can insert com-ments on a separate line or at the end of a line of code, but you can’t insert comcom-ments at the end ments on a separate line or at the end of a line of code, but you can’t insert comments at the end of a code line that contains a line-continuation marker (_). (To download an executable version of  of a code line that contains a line-continuation marker (_). (To download an executable version of  L

Lististing 1, ing 1, go go to to http://http:// wwwwww .winnetmag.com/.winnetmag.com/ ffililes/es/ 55550505// 55550505.zi.zip.)p.)

The third rule is that VBScript doesn’t care about extra white space. Adding extra spaces or The third rule is that VBScript doesn’t care about extra white space. Adding extra spaces or blank lines can often improve the code’s readability. VBScript ignores the blank lines and the extra blank lines can often improve the code’s readability. VBScript ignores the blank lines and the extra spaces between the variable name and the assignment operator (=).

spaces between the variable name and the assignment operator (=).

The fourth rule is that although VBScript doesn’t impose a maximum line length, breaking long The fourth rule is that although VBScript doesn’t impose a maximum line length, breaking long lines into multiple short lines can improve the readability of a script. In VBScript, you can use the lines into multiple short lines can improve the readability of a script. In VBScript, you can use the continuation marker to let a statement or line of code span multiple lines. I often use the continuation marker to let a statement or line of code span multiple lines. I often use the line-continuation marker when I initialize dynamic arrays (e.g., at callout A in Listing 1) or to pass a continuation marker when I initialize dynamic arrays (e.g., at callout A in Listing 1) or to pass a

(8)

long string to WScript’s Echo method (WScript.Echo), which I demonstrate several times in the body long string to WScript’s Echo method (WScript.Echo), which I demonstrate several times in the body of the demo.vbs script. When you use the line-continuation marker, you need to include one space of the demo.vbs script. When you use the line-continuation marker, you need to include one space immediately before the underscore, or you will encounter an error with some statement types. immediately before the underscore, or you will encounter an error with some statement types.

On the flip side of rule 4 is the fifth VBScript ground rule, which lets one line of code contain On the flip side of rule 4 is the fifth VBScript ground rule, which lets one line of code contain multiple statements. In VBScript, you can use a colon (:) to separate multiple statements within a multiple statements. In VBScript, you can use a colon (:) to separate multiple statements within a line of code. In the code line

line of code. In the code line

Dim strText: strText = “WSH ROCKS!” : WScript.Echo strText Dim strText: strText = “WSH ROCKS!” : WScript.Echo strText

statement 1 is Dim strText, statement 2 is strText = “WSH ROCKS!”, and statement 3 is WScript.Echo statement 1 is Dim strText, statement 2 is strText = “WSH ROCKS!”, and statement 3 is WScript.Echo strText. Although VBScript supports this capability, I generally don’t use it.

strText. Although VBScript supports this capability, I generally don’t use it.

The sixth VBScript rule is that you must terminate each line of VBScript code with a new-line The sixth VBScript rule is that you must terminate each line of VBScript code with a new-line character. Pressing Enter automatically inserts the new-line character. VBScript doesn’t use the character. Pressing Enter automatically inserts the new-line character. VBScript doesn’t use the vis-ible line terminator (;) that JScript and Perl use.

ible line terminator (;) that JScript and Perl use.

The seventh and final ground rule I want to establish governs VBScript identifiers (e.g., The seventh and final ground rule I want to establish governs VBScript identifiers (e.g., vari-ables, constants, function names, subroutine names). Identifiers can’t exceed 255 characters in ables, constants, function names, subroutine names). Identifiers can’t exceed 255 characters in length and must begin with an uppercase or lowercase letter of the alphabet.

length and must begin with an uppercase or lowercase letter of the alphabet.

Listing 1

Listing 1

 Demo.vbs  Demo.vbs ’ ’ ** ‘ demo.vbs ‘ demo.vbs ‘ ‘ **

‘ Declaration and Initialization Section ‘ Declaration and Initialization Section ‘

‘ **

Rem *** Script Directives *** Rem *** Script Directives *** Option Explicit

Option Explicit On Error Resume Next On Error Resume Next

Rem *** Variable Declarations *** Rem *** Variable Declarations ***

Dim objFileSystem, objShell, objLogFile, objTempFile Dim objFileSystem, objShell, objLogFile, objTempFile Dim arrStrings, intReturnCode

Dim arrStrings, intReturnCode

Dim strBuffer, strLogFile, strTempFile Dim strBuffer, strLogFile, strTempFile Rem *** Constant Definitions *** Rem *** Constant Definitions *** Const OpenFileForReading = 1 Const OpenFileForReading = 1

Rem *** Variable Initialization *** Rem *** Variable Initialization *** intReturnCode = 0

intReturnCode = 0 s

sttrrBBuuffffeerr = = ““”” st

strLrLogogFiFilele = “= “c:c:\” \” & S& Splplitit(W(WScScririptpt.S.ScrcripiptNtNamame, e, “.“.”)”)(0(0) & ) & “.“.lolog”g” s

sttrrTTeemmppFFiillee = = ““cc::\\tteemmpp..ttxxtt”” a

arrrSrSttrrininggss = A= Arrrarayy((“a“abbccdedeffgghihijjkklmlmnnopopqqrrststuuvvwxwxyyzz”, ”, __

A

A

“ABCDEFGHIJKLMNOPQRSTUVWXYZ”, _

“ABCDEFGHIJKLMNOPQRSTUVWXYZ”, _

“the quick brown fox jumps over the lazy dogs back”) “the quick brown fox jumps over the lazy dogs back”) ‘ Script Body Section

‘ Script Body Section ‘

‘ **

‘ Using If-Then-End If to demonstrate the On Error Resume Next statement.

‘ Using If-Then-End If to demonstrate the On Error Resume Next statement.

B

B

If Err.Number Then

If Err.Number Then

WScript.Echo “Bob’s Friendly Error Message” & vbNewLine & _ WScript.Echo “Bob’s Friendly Error Message” & vbNewLine & _ “Error Number: “ & Err.Number & vbNewLine & _

“Error Number: “ & Err.Number & vbNewLine & _ “Error Description: “ & Err.Description “Error Description: “ & Err.Description Err.Clear

Err.Clear End If End If

‘ Create scripting runtime FileSystemObject. ‘ Create scripting runtime FileSystemObject. ‘ Create TextStream object for script’s log file. ‘ Create TextStream object for script’s log file. ‘ Write starting line to log file.

‘ Write starting line to log file.

Continued  Continued 

2

(9)

Listing 1:

Listing 1:continued continued 

Set objFileSystem = CreateObject(“Scripting.FileSystemObject”) Set objFileSystem = CreateObject(“Scripting.FileSystemObject”) Set objLogFile = objFileSystem.CreateTextFile(strLogFile, TRUE) Set objLogFile = objFileSystem.CreateTextFile(strLogFile, TRUE)

objLogFile.WriteLine(Now & “:” & vbTab & WScript.ScriptFullName & “ Started.”) objLogFile.WriteLine(Now & “:” & vbTab & WScript.ScriptFullName & “ Started.”) ‘ Create WSH Shell object.

‘ Create WSH Shell object.

‘ Run external command redirecting commands output to temporary file. ‘ Run external command redirecting commands output to temporary file. ‘ Check for error condition and write appropriate message to log file. ‘ Check for error condition and write appropriate message to log file. Set objShell = WScript.CreateObject(“WScript.Shell”)

Set objShell = WScript.CreateObject(“WScript.Shell”)

intReturnCode = objShell.Run(“cmd /C ipconfig.exe >” & strTempFile, 0, TRUE) intReturnCode = objShell.Run(“cmd /C ipconfig.exe >” & strTempFile, 0, TRUE) If Err.Number Then

If Err.Number Then

objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) Err.Clear

Err.Clear Else

Else

objLogFile.WriteLine(Now & “:” & vbTab & “Run completed successfully.”) objLogFile.WriteLine(Now & “:” & vbTab & “Run completed successfully.”) End If

End If

‘ Create TextStream object to read in c:\temp.txt file, which the run command created. ‘ Create TextStream object to read in c:\temp.txt file, which the run command created. ‘ Read entire file into buffer using the TextStream objects ReadAll method.

‘ Read entire file into buffer using the TextStream objects ReadAll method. ‘ Check for error and write appropriate message to log file.

‘ Check for error and write appropriate message to log file. ‘ Close TextStream object.

‘ Close TextStream object.

Set objTempFile = objFileSystem.OpenTextFile(strTempFile, OpenFileForReading) Set objTempFile = objFileSystem.OpenTextFile(strTempFile, OpenFileForReading) strBuffer = objTempFile.ReadAll

strBuffer = objTempFile.ReadAll If Err.Number Then

If Err.Number Then

objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) Err.Clear

Err.Clear Else

Else

objLogFile.WriteLine(Now & “:” & vbTab & “Open and read “ & strTempFile & _ objLogFile.WriteLine(Now & “:” & vbTab & “Open and read “ & strTempFile & _

“ completed successfully.”) “ completed successfully.”) End If End If objTempFile.Close objTempFile.Close

‘ Display the buffer contents that are the redirected result of the run ‘ Display the buffer contents that are the redirected result of the run ‘ command.

‘ command.

WScript.Echo strBuffer WScript.Echo strBuffer ‘ Delete c:\temp.txt file. ‘ Delete c:\temp.txt file.

‘ Check for error and write appropriate message to log file. ‘ Check for error and write appropriate message to log file. objFileSystem.DeleteFile(strTempFile)

objFileSystem.DeleteFile(strTempFile) If Err.Number Then

If Err.Number Then

objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) Err.Clear

Err.Clear Else

Else

objLogFile.WriteLine(Now & “:” & vbTab & “Delete “ & strTempFile & _ objLogFile.WriteLine(Now & “:” & vbTab & “Delete “ & strTempFile & _

“ completed successfully.”) “ completed successfully.”) End If

End If

‘ Write closing line to log file and close log file. ‘ Write closing line to log file and close log file.

objLogFile.WriteLine(Now & “:” & vbTab & WScript.ScriptFullName & “ Finished.”) objLogFile.WriteLine(Now & “:” & vbTab & WScript.ScriptFullName & “ Finished.”) objLogFile.Close

objLogFile.Close

‘ Create TextStream object to read in log file. ‘ Create TextStream object to read in log file.

‘ Read entire file into buffer using the TextStream objects ReadAll method. ‘ Read entire file into buffer using the TextStream objects ReadAll method. ‘ Close TextStream object.

‘ Close TextStream object.

Set objLogFile = objFileSystem.OpenTextFile(strLogFile, OpenFileForReading) Set objLogFile = objFileSystem.OpenTextFile(strLogFile, OpenFileForReading) strBuffer = objLogFile.ReadAll

strBuffer = objLogFile.ReadAll objLogFile.Close

objLogFile.Close

‘ Display the buffer’s content, which is the log file in this case. ‘ Display the buffer’s content, which is the log file in this case. WScript.Echo strBuffer

WScript.Echo strBuffer

‘ Delete the log file, release object references, and exit script. ‘ Delete the log file, release object references, and exit script. objFileSystem.DeleteFile(strLogFile)

objFileSystem.DeleteFile(strLogFile) Set objShell = Nothing

Set objShell = Nothing Set objFileSystem = Nothing Set objFileSystem = Nothing WScript.Quit(0) WScript.Quit(0) ‘ ‘ ** ‘ * demo.vbs end ‘ * demo.vbs end Cha

(10)

Declaration and Initialization

Declaration and Initialization

The primary elements that make up declaration and initialization are script directives, variable The primary elements that make up declaration and initialization are script directives, variable dec-larations, variable initialization, and constant definitions. All these elements (with the possible larations, variable initialization, and constant definitions. All these elements (with the possible exception of initialization) are optional. However, using these language features can help you exception of initialization) are optional. However, using these language features can help you pro-duce scripts that are easier to debug and maintain.

duce scripts that are easier to debug and maintain.

VBScript Directives 

VBScript Directives 

VBScript includes two directives or statements that significantly affect the runtime behavior of scripts. VBScript includes two directives or statements that significantly affect the runtime behavior of scripts. The two directives are the Option Explicit statement and the On Error Resume Next statement. The two directives are the Option Explicit statement and the On Error Resume Next statement.

The Option Explicit statement requires that you declare (i.e., define) all script variables via a The Option Explicit statement requires that you declare (i.e., define) all script variables via a VBScript Dim statement before you use the variables in an expression. When you use Option VBScript Dim statement before you use the variables in an expression. When you use Option Explicit, the declaration requirement applies throughout the entire script, including variables in the Explicit, the declaration requirement applies throughout the entire script, including variables in the main body of the script and variables in user-defined functions and subroutines. You must include main body of the script and variables in user-defined functions and subroutines. You must include the Option Explicit statement before any other statements in your script. Therefore, you always the Option Explicit statement before any other statements in your script. Therefore, you always find Option Explicit at the top of scripts that use it. The benefit of using Option Explicit is that an find Option Explicit at the top of scripts that use it. The benefit of using Option Explicit is that an error occurs whenever the VBScript interpreter encounters an undefined variable during script error occurs whenever the VBScript interpreter encounters an undefined variable during script exe-cution. Using Option Explicit helps you isolate typographical mistakes and variables with incorrect cution. Using Option Explicit helps you isolate typographical mistakes and variables with incorrect

scopes

scopes(a scope defines the visibility of a variable to other parts of the script such as functions and(a scope defines the visibility of a variable to other parts of the script such as functions and subroutines).

subroutines).

The On Error Resume Next statement controls how a script notifies you when a script The On Error Resume Next statement controls how a script notifies you when a script encoun-ters a runtime error. When a script runtime error occurs and the script doesn’t use the On Error ters a runtime error. When a script runtime error occurs and the script doesn’t use the On Error Resume Next statement, WSH displays a dialog box containing the execution error information and Resume Next statement, WSH displays a dialog box containing the execution error information and aborts the script. Figure 1 shows an example WSH Script Execution Error dialog box. Including an aborts the script. Figure 1 shows an example WSH Script Execution Error dialog box. Including an On Error Resume Next statement in a script effectively tells VBScript to continue execution despite On Error Resume Next statement in a script effectively tells VBScript to continue execution despite a runtime error: VBScript’s built-in Err object is set with the corresponding error information, and a runtime error: VBScript’s built-in Err object is set with the corresponding error information, and the script continues. The On Error Resume Next statement lets you trap errors and respond to them the script continues. The On Error Resume Next statement lets you trap errors and respond to them programmatically. You can choose to display a friendly, descriptive message or write the error programmatically. You can choose to display a friendly, descriptive message or write the error information to a log file. Figure 2 shows an example customized error dialog box.

information to a log file. Figure 2 shows an example customized error dialog box.

Using On Error Resume Next to help trap errors is important. Suppose I comment out (i.e., Using On Error Resume Next to help trap errors is important. Suppose I comment out (i.e., add Rem to the beginning of) the line that declares variable intReturnCode at the beginning of  add Rem to the beginning of) the line that declares variable intReturnCode at the beginning of  demo.vbs:

demo.vbs:

Rem Dim arrStrings, intReturnCode Rem Dim arrStrings, intReturnCode

If I execute this modified script, the script will run to completion, but it might not produce the If I execute this modified script, the script will run to completion, but it might not produce the desired result. The script won’t display the standard WSH Script Execution Error message on the desired result. The script won’t display the standard WSH Script Execution Error message on the console; instead, the script will produce Figure 2’s custom error dialog box, which states that a console; instead, the script will produce Figure 2’s custom error dialog box, which states that a script variable is undefined. The

script variable is undefined. The If-Then-End If  If-Then-End If statement at callout B in Listing 1 acts as a rudi-statement at callout B in Listing 1 acts as a rudi-mentary error-handling routine that echos the contents of the VBScript Err object’s Number and mentary error-handling routine that echos the contents of the VBScript Err object’s Number and Description properties. After you click OK to acknowledge the error dialog box, the script Description properties. After you click OK to acknowledge the error dialog box, the script con-tinues because the On Error Resume Next directive tells the script to proceed despite the error. (If  tinues because the On Error Resume Next directive tells the script to proceed despite the error. (If  I commented out the On Error Resume Next directive and ran the script again, Figure 1’s WSH I commented out the On Error Resume Next directive and ran the script again, Figure 1’s WSH Script Execution Error dialog box would display. More important, the script would abort as soon as Script Execution Error dialog box would display. More important, the script would abort as soon as I clicked OK in Figure 1’s dialog box; I’d have no control over the remainder of the script. The I clicked OK in Figure 1’s dialog box; I’d have no control over the remainder of the script. The

4

(11)

only benefit of not using On Error Resume Next is that the error information in the WSH Script only benefit of not using On Error Resume Next is that the error information in the WSH Script Execution Error dialog box can be more descriptive than the information in the Err object’s Execution Error dialog box can be more descriptive than the information in the Err object’s Description property. Figure 1 not only includes the name of the undefined variable, it also Description property. Figure 1 not only includes the name of the undefined variable, it also pro-vides the specific line number for the error. In Figure 2, the error description simply states that the vides the specific line number for the error. In Figure 2, the error description simply states that the script tried to use an undefined variable.)

script tried to use an undefined variable.)

Figure 1

Figure 1

 Example WSH Script Execution Error dialog box  Example WSH Script Execution Error dialog box

Figure 2

Figure 2

 A customized error dialog box  A customized error dialog box

Why does an error occur? In demo.vbs, I initialize intReturnCode to 0 in line 19 of the script, a Why does an error occur? In demo.vbs, I initialize intReturnCode to 0 in line 19 of the script, a few lines before callout A. But because I specified the Option Explicit directive at the start of the few lines before callout A. But because I specified the Option Explicit directive at the start of the script and commented out intReturnCode’s declaration statement, an error occurs when the script script and commented out intReturnCode’s declaration statement, an error occurs when the script tries to execute the line that initializes the undeclared intReturnCode to 0. I can eliminate this error tries to execute the line that initializes the undeclared intReturnCode to 0. I can eliminate this error and other potential variable declaration errors by removing the Option Explicit statement. and other potential variable declaration errors by removing the Option Explicit statement. How-ever, a better way to fix the problem is to define the undeclared variable (in this case, remove the ever, a better way to fix the problem is to define the undeclared variable (in this case, remove the Rem from the declaration statement):

Rem from the declaration statement):

Dim arrStrings, intReturnCode Dim arrStrings, intReturnCode

Cha

(12)

Unlike Option Explicit, which affects the entire script, On Error Resume Next applies to only the Unlike Option Explicit, which affects the entire script, On Error Resume Next applies to only the portion of the script (e.g., the script’s body, a function, a subroutine) that defines it. On Error portion of the script (e.g., the script’s body, a function, a subroutine) that defines it. On Error Resume Next’s narrow scope lets you control precisely when and where it’s in effect. (VBScript Resume Next’s narrow scope lets you control precisely when and where it’s in effect. (VBScript doesn’t support Visual Basic’s—VB’s—On Error Goto Label construct.) When you use the Option doesn’t support Visual Basic’s—VB’s—On Error Goto Label construct.) When you use the Option Explicit and On Error Resume Next directives correctly, they can make VBScript routines more Explicit and On Error Resume Next directives correctly, they can make VBScript routines more robust and user-friendly and play an important role in debugging scripts.

robust and user-friendly and play an important role in debugging scripts.

VBScript Variables 

VBScript Variables 

Earlier, I said declaring variables in VBScript is optional—and it is. However, engaging in the Earlier, I said declaring variables in VBScript is optional—and it is. However, engaging in the exer-cise of defining your script’s variables can be well worth your time and effort for several reasons, cise of defining your script’s variables can be well worth your time and effort for several reasons, such as debugging and script maintenance. Declaring your script’s variables also requires you to such as debugging and script maintenance. Declaring your script’s variables also requires you to consider the environment and objects with which your script interacts, which can result in consider the environment and objects with which your script interacts, which can result in better-designed scripts that do what you intend them to do.

designed scripts that do what you intend them to do.

A VBScript variable is simply a named memory location that contains some value. The value A VBScript variable is simply a named memory location that contains some value. The value might be a number, a string, or some other data type that the language supports. The variable might be a number, a string, or some other data type that the language supports. The variable name is the mechanism through which you assign a value to a variable. Declaring VBScript name is the mechanism through which you assign a value to a variable. Declaring VBScript vari-ables identifies the names that you’ll use to refer to the data your script manipulates.

ables identifies the names that you’ll use to refer to the data your script manipulates.

You use the Dim statement to declare VBScript variables. In demo.vbs, the variable You use the Dim statement to declare VBScript variables. In demo.vbs, the variable declara-tions follow the script directives at the beginning of the script. VBScript supports one primary data tions follow the script directives at the beginning of the script. VBScript supports one primary data type:

type: variant.variant. You can think of variants as general-purpose variables that aren’t bound to a specificYou can think of variants as general-purpose variables that aren’t bound to a specific type. When you declare a VBScript variable using Dim, you don’t supply additional type type. When you declare a VBScript variable using Dim, you don’t supply additional type informa-tion as you do in VB. Instead, VBScript determines a variable’s type at runtime, based on the tion as you do in VB. Instead, VBScript determines a variable’s type at runtime, based on the vari-able’s contents and the usage context. VBScript supports many different data subtypes and

able’s contents and the usage context. VBScript supports many different data subtypes and corresponding data conversion functions that let you morph variants to your heart’s content. For corresponding data conversion functions that let you morph variants to your heart’s content. For more information about VBScript variables, download the free VBScript HTML Help file

more information about VBScript variables, download the free VBScript HTML Help file (vbsdoc.exe) at http://msdn.microsoft.com/scripting/vbscript/download/vbsdoc.exe. (vbsdoc.exe) at http://msdn.microsoft.com/scripting/vbscript/download/vbsdoc.exe.

Variable Initialization 

Variable Initialization 

Variable initialization is nothing more than assigning a known value to a variable before you use Variable initialization is nothing more than assigning a known value to a variable before you use the variable. In demo.vbs, I initialize several variables before using the variables in the script’s the variable. In demo.vbs, I initialize several variables before using the variables in the script’s body. You can initialize a variable to one value, such as a number or a string, or to a more body. You can initialize a variable to one value, such as a number or a string, or to a more com-plex value constructed from multiple elements.

plex value constructed from multiple elements.

For example, in the variable initialization section of demo.vbs, the script assigns to strLogFile For example, in the variable initialization section of demo.vbs, the script assigns to strLogFile the co

the co ncatencatenation nation (fr(from VBom VBSScript’cript’s & s & opop erator) oerator) o f tf three hree subsubstristrings. The first sngs. The first sububstring (“string (“c:\c:\ ””) and) and third substring (“.log”) are straightforward. The second or middle substring retrieves the value of  third substring (“.log”) are straightforward. The second or middle substring retrieves the value of  WScript’s ScriptName property (in this case, “demo.vbs”) and splits the string into two strings at the WScript’s ScriptName property (in this case, “demo.vbs”) and splits the string into two strings at the dot (.). In this example, I append the subscript (0) to the end of the function call to force the Split dot (.). In this example, I append the subscript (0) to the end of the function call to force the Split function to return only the first element (“demo”) of the array of elements that Split ordinarily function to return only the first element (“demo”) of the array of elements that Split ordinarily returns. The end result is a log file name that is identical to the script name without the extension. returns. The end result is a log file name that is identical to the script name without the extension.

Constant Definitions 

Constant Definitions 

Constants are named values that don’t change throughout the execution of a script. VBScript Constants are named values that don’t change throughout the execution of a script. VBScript sup-ports two types of constants:

ports two types of constants: literalliteral andand intrinsic.intrinsic. Literal constants are constants that you define forLiteral constants are constants that you define for the purpose of making your script more intelligible. Let’s say that you write a script that uses the the purpose of making your script more intelligible. Let’s say that you write a script that uses the

6

(13)

value of Pi. Rather than hard-coding the numeric value each time the script needs it, you might value of Pi. Rather than hard-coding the numeric value each time the script needs it, you might define the following literal constant: Const Pi = 3.1415926535897932384626433832795. When you define the following literal constant: Const Pi = 3.1415926535897932384626433832795. When you need to reference the value of Pi in your script, you simply use the constant’s name (i.e., Pi). In need to reference the value of Pi in your script, you simply use the constant’s name (i.e., Pi). In this example, referring to the name is much easier than (and significantly reduces potential typing this example, referring to the name is much easier than (and significantly reduces potential typing errors from) coding the numeric value each time the script needs to use Pi. Furthermore, if you errors from) coding the numeric value each time the script needs to use Pi. Furthermore, if you need to change the value of a constant at some later date, you need to update the constant’s value need to change the value of a constant at some later date, you need to update the constant’s value in only one place in the script: in the line where you defined the constant. You can assign only in only one place in the script: in the line where you defined the constant. You can assign only scalar values to VBScript literal constants. The language doesn’t support constants constructed from scalar values to VBScript literal constants. The language doesn’t support constants constructed from other constants or expressions.

other constants or expressions.

Intrinsic constants are constants that are built into the VBScript language to make the language Intrinsic constants are constants that are built into the VBScript language to make the language easier to use and make your scripts easier to read and maintain. Some of my favorite intrinsic easier to use and make your scripts easier to read and maintain. Some of my favorite intrinsic con-stants include the escape sequence concon-stants such as vbNewLine and vbTab that represent ANSI stants include the escape sequence constants such as vbNewLine and vbTab that represent ANSI character codes, which you’ll find sprinkled throughout demo.vbs. The VBScript Language character codes, which you’ll find sprinkled throughout demo.vbs. The VBScript Language Refer-ence and the Scripting Run-Time ReferRefer-ence in the VBScript Help file provide a complete list of  ence and the Scripting Run-Time Reference in the VBScript Help file provide a complete list of  constants.

constants.

VBScript doesn’t let you use constants that other objects, such as the scripting runtime’s VBScript doesn’t let you use constants that other objects, such as the scripting runtime’s

FileSystemObject and ADSI, define. However, Microsoft plans to include this capability in the next FileSystemObject and ADSI, define. However, Microsoft plans to include this capability in the next release of WSH. In the interim, if you want to use constants that other objects define, simply release of WSH. In the interim, if you want to use constants that other objects define, simply dupli-cate the constant definition in your script. In the constant definitions section of demo.vbs, I define cate the constant definition in your script. In the constant definitions section of demo.vbs, I define the local constant OpenFileForReading to mimic the behavior of FileSystemObject’s the local constant OpenFileForReading to mimic the behavior of FileSystemObject’s OpenFileFor-Reading constant.

Reading constant.

Demo.vbs End

Demo.vbs End

Before I go, I should tell you what the demo script in Listing 1 does. Demo.vbs simply runs Before I go, I should tell you what the demo script in Listing 1 does. Demo.vbs simply runs NT’s ipconfig.exe utility, writes the commands’ output to a file, opens and displays the file, NT’s ipconfig.exe utility, writes the commands’ output to a file, opens and displays the file, deletes the file, and records the success or failure of each major action along the way to a log deletes the file, and records the success or failure of each major action along the way to a log file. Then, demo.vbs opens the resulting log file, displays the file, deletes the file, and exits. In file. Then, demo.vbs opens the resulting log file, displays the file, deletes the file, and exits. In Chapter 2, I’ll examine one of the more important elements generally found in the body of a Chapter 2, I’ll examine one of the more important elements generally found in the body of a script: object handling.

script: object handling.

Cha

(14)
(15)

Chapter 2

Chapter 2

Scripting 101: Working with Objects

Scripting 101: Working with Objects

By Bob Wells 

By Bob Wells 

In Chapter 1, I explained how to declare and initialize variables in Windows Script Host (WSH) In Chapter 1, I explained how to declare and initialize variables in Windows Script Host (WSH) scripts that you create using VBScript. In this chapter, I discuss the most important job you scripts that you create using VBScript. In this chapter, I discuss the most important job you per-form in the script body: working with objects.

form in the script body: working with objects.

Objects

Objects

Regardless of the tasks your scripts perform, at some point you’ll create and interact with objects. Regardless of the tasks your scripts perform, at some point you’ll create and interact with objects. Whether implicitly or explicitly, all WSH scripts create objects. Understanding what an object is, Whether implicitly or explicitly, all WSH scripts create objects. Understanding what an object is, what an object provides, and how to create and interact with objects is key to successfully using what an object provides, and how to create and interact with objects is key to successfully using WSH. Although working with objects might be old hat to those of you with a Visual Basic (VB) WSH. Although working with objects might be old hat to those of you with a Visual Basic (VB) background, quite the opposite is true for individuals with only a batch file background.

background, quite the opposite is true for individuals with only a batch file background.

Objects vs. Utilities

Objects vs. Utilities

WSH scripts and batch files have numerous significant differences, but none more important than WSH scripts and batch files have numerous significant differences, but none more important than the transition away from utilities and toward objects. Historically, developers used batch files to the transition away from utilities and toward objects. Historically, developers used batch files to glue together system, resource kit, and third-party command-line utilities. Provided that you found glue together system, resource kit, and third-party command-line utilities. Provided that you found utilities to support all the tasks that you wanted to perform, this approach worked fine. utilities to support all the tasks that you wanted to perform, this approach worked fine. Unfortu-nately, developers often hit roadblocks along the way. If the utility the batch file called failed to nately, developers often hit roadblocks along the way. If the utility the batch file called failed to provide some required option, the developer had to scour the Internet for another utility to fill the provide some required option, the developer had to scour the Internet for another utility to fill the void. Sound familiar?

void. Sound familiar?

Figure 1 shows how Windows NT’s graphical applications and utilities call Win32 APIs to run Figure 1 shows how Windows NT’s graphical applications and utilities call Win32 APIs to run the task that the application or utility performs. Unfortunately, Win32 APIs aren’t suitable for ad hoc the task that the application or utility performs. Unfortunately, Win32 APIs aren’t suitable for ad hoc scripts, and calling Win32 APIs from scripts is almost impossible. Therefore, NT limited scripting to scripts, and calling Win32 APIs from scripts is almost impossible. Therefore, NT limited scripting to the functionality that the utilities provided. This limitation led to a perception that Windows was the functionality that the utilities provided. This limitation led to a perception that Windows was scripting-challenged (especially compared to UNIX). In fact, the limited functionality led to a scripting-challenged (especially compared to UNIX). In fact, the limited functionality led to a prolif-eration of third-party and open-source scripting tools to address the lack of Win32 scriptability. eration of third-party and open-source scripting tools to address the lack of Win32 scriptability. So what has changed? As I’ve mentioned, part of the solution is WSH. WSH interacts with So what has changed? As I’ve mentioned, part of the solution is WSH. WSH interacts with objects, specifically COM automation objects, to eliminate the need to find utilities that support all objects, specifically COM automation objects, to eliminate the need to find utilities that support all the tasks you want to perform. WSH provides a lightweight scripting environment capable of  the tasks you want to perform. WSH provides a lightweight scripting environment capable of  calling the same set of system services that the native NT graphical applications call.

calling the same set of system services that the native NT graphical applications call.

The more significant piece of the solution pertains to the API. As Figure 2 shows, Microsoft is The more significant piece of the solution pertains to the API. As Figure 2 shows, Microsoft is using COM to expose almost all system services in such a way that scripts and more traditional using COM to expose almost all system services in such a way that scripts and more traditional system programming languages (e.g., C++) call the same set of interfaces to perform a desired system programming languages (e.g., C++) call the same set of interfaces to perform a desired task. How is this standardization possible? With COM, system and application developers can task. How is this standardization possible? With COM, system and application developers can develop their applications so that COM-aware scripting environments, such as WSH, can interact develop their applications so that COM-aware scripting environments, such as WSH, can interact with and control COM-enabled services and applications.

with and control COM-enabled services and applications.

9

9

(16)

Figure 1

Figure 1

 How NT’s graphical applications and utilities call Win32 APIs to  How NT’s graphical applications and utilities call Win32 APIs to

run the task that the application or utility performs run the task that the application or utility performs

Figure 2

Figure 2

COM exposing system services COM exposing system services

For example, in addition to abstracting multiple and disparate directory services, Active For example, in addition to abstracting multiple and disparate directory services, Active Direc-tory Service Interfaces (ADSI) lets scripts call the same ADSI services that the native Windows 2000 tory Service Interfaces (ADSI) lets scripts call the same ADSI services that the native Windows 2000 Active Directory (AD) management tools use. Similarly, Windows Management Instrumentation Active Directory (AD) management tools use. Similarly, Windows Management Instrumentation

Win32 API Win32 API MMC MMC System and System and Performance Performance Data Data Service Service Control Control Manager Manager SAM SAM  Active  Active Directory Directory Registry Registry Event Event Log Log MMC Active MMC Active Directory Snap-In Directory Snap-In Batch Batch Files Files C:\>utilities C:\>utilities

COM-Enabled System Services (ADO, ADSI, CDO, WMI) COM-Enabled System Services (ADO, ADSI, CDO, WMI)

WSH WSH Scripts Scripts OK  OK  User Manager User Manager Win32 API Win32 API Server Manager Server Manager C:\>utilities C:\>utilities Scripts Scripts Performance Performance Data Data System System Data Data Service Service Control Control Manager Manager SAM SAM Registry Registry Event Event Log Log OK  OK 

10

(17)

(WMI) provides COM-savvy scripts with the ability to fetch, read, and set the same set of Win32 (WMI) provides COM-savvy scripts with the ability to fetch, read, and set the same set of Win32 system and performance data that Microsoft Systems Management Server (SMS) 2.0 and other system and performance data that Microsoft Systems Management Server (SMS) 2.0 and other Web-Based Enterprise Management (WBEM)-enabled systems management applications access. You Based Enterprise Management (WBEM)-enabled systems management applications access. You leverage these services by utilizing these COM objects in your scripts. The first step is to leverage these services by utilizing these COM objects in your scripts. The first step is to under-stand what an object is.

stand what an object is.

What Is an Object?

What Is an Object?

An object is simply a

An object is simply a thing.thing. Each object has a set of characteristics or attributes that describe theEach object has a set of characteristics or attributes that describe the object and the actions it performs. Network OSs, messaging systems, applications, and object and the actions it performs. Network OSs, messaging systems, applications, and program-ming languages generally classify objects in terms of a user, a group, a computer, a printer, a ming languages generally classify objects in terms of a user, a group, a computer, a printer, a net-work, or an application. These entities are all objects in the IT world. Each of these objects has a work, or an application. These entities are all objects in the IT world. Each of these objects has a set of 

set of  properties propertiesthat uniquely describe it. Each object might also perform an action using itsthat uniquely describe it. Each object might also perform an action using its

methods.

methods. So in the computer world, properties describe an object, and objects use methods to per-So in the computer world, properties describe an object, and objects use methods to per-form actions.

form actions.

Let’s consider a user object. Properties of a user object might include username, full name, and Let’s consider a user object. Properties of a user object might include username, full name, and password. A user object might use methods to create, delete, or set passwords. You must have a password. A user object might use methods to create, delete, or set passwords. You must have a user object before you can interact with it, so let’s take a look at how to create objects.

user object before you can interact with it, so let’s take a look at how to create objects.

Creating Objects

Creating Objects

You might be interested to learn that WSH is a set of objects. WSH includes three primary objects: You might be interested to learn that WSH is a set of objects. WSH includes three primary objects: WScript, Network, and Shell. The WScript object provides the script execution environment. The WScript, Network, and Shell. The WScript object provides the script execution environment. The Network object provides properties and methods typically associated with network and printer Network object provides properties and methods typically associated with network and printer connections. The Shell object provides methods and properties associated with the desktop shell, connections. The Shell object provides methods and properties associated with the desktop shell, environment variables, and the registry.

environment variables, and the registry.

Before you can access an object’s methods and properties, you must first create an instance of  Before you can access an object’s methods and properties, you must first create an instance of  the object. As part of the script execution environment, WScript includes two the object. As part of the script execution environment, WScript includes two methods—CreateOb- ject and GetObject—that you can use to create objects. Using these methods is a concept that  ject and GetObject—that you can use to create objects. Using these methods is a concept that

rep-resents a radical departure from calling utilities inside of batch files. resents a radical departure from calling utilities inside of batch files.

VBScript also provides CreateObject and GetObject as functions, which you’ll generally want VBScript also provides CreateObject and GetObject as functions, which you’ll generally want to use rather than the WScript methods. Using WScript’s CreateObject or GetObject methods adds to use rather than the WScript methods. Using WScript’s CreateObject or GetObject methods adds an additional layer of work and is slightly less efficient than using the analogous VBScript an additional layer of work and is slightly less efficient than using the analogous VBScript func-tions. WScript includes these methods to support third-party script engines that might not provide tions. WScript includes these methods to support third-party script engines that might not provide a mechanism to create objects.

a mechanism to create objects.

Before we look at some examples, you need to be aware of a couple of exceptions to the Before we look at some examples, you need to be aware of a couple of exceptions to the requirement that you create the object before you use it. The first exception concerns WScript. requirement that you create the object before you use it. The first exception concerns WScript. Recall that I said every WSH script creates objects. Running a WSH script implicitly creates a Recall that I said every WSH script creates objects. Running a WSH script implicitly creates a WScript object. Therefore, you can call any WScript method or read any WScript property without WScript object. Therefore, you can call any WScript method or read any WScript property without an explicit call to CreateObject.

an explicit call to CreateObject.

The VBScript Err object is the second object that WSH scripts automatically create. For more The VBScript Err object is the second object that WSH scripts automatically create. For more information about the VBScript Err object, see Chapter 1. Now, let’s create some objects. A good information about the VBScript Err object, see Chapter 1. Now, let’s create some objects. A good place to start is with syntax and definitions.

place to start is with syntax and definitions.

Cha

(18)

CreateObject 

CreateObject 

The CreateObject function creates and returns a reference to an automation object. The function The CreateObject function creates and returns a reference to an automation object. The function has one mandatory parameter and one optional parameter. In the code line

has one mandatory parameter and one optional parameter. In the code line

Set objReference = CreateObject(“strApp.strObj” [, “strServerName”]) Set objReference = CreateObject(“strApp.strObj” [, “strServerName”])

the mandatory two-part parameter is strApp.strObj, which identifies the name of the application or the mandatory two-part parameter is strApp.strObj, which identifies the name of the application or component containing the target object and the class name of the object to create. This application component containing the target object and the class name of the object to create. This application and object pair is also a programmatic identifier (ProgID). The optional parameter, strServerName, and object pair is also a programmatic identifier (ProgID). The optional parameter, strServerName, identifies the name of the server on which the target object resides. When supported, identifies the name of the server on which the target object resides. When supported, strServer-Name lets you create and interact with objects installed on remote machines. Microsoft added this Name lets you create and interact with objects installed on remote machines. Microsoft added this feature to the CreateObject function in VB 6.0 and expects to include the feature in the Win2K feature to the CreateObject function in VB 6.0 and expects to include the feature in the Win2K WSH and VBScript releases.

WSH and VBScript releases.

CreateObject returns a reference to the newly created object. Typically, you assign the CreateObject returns a reference to the newly created object. Typically, you assign the refer-ence to an object variable so that you can interact with the object within your script. In the ence to an object variable so that you can interact with the object within your script. In the pre-vious code line, VBScript’s Set statement assigns the object reference that CreateObject returns to vious code line, VBScript’s Set statement assigns the object reference that CreateObject returns to the objReference variable. After you obtain a valid object reference, you can invoke the object’s the objReference variable. After you obtain a valid object reference, you can invoke the object’s methods and read or set the object’s properties. The objects.vbs example script in Listing 1 methods and read or set the object’s properties. The objects.vbs example script in Listing 1 demon-strates how to use the WScript CreateObject method and VBScript’s CreateObject function.

strates how to use the WScript CreateObject method and VBScript’s CreateObject function. At callout A, you can see that WScript methods (WScript.Echo) and properties (e.g., At callout A, you can see that WScript methods (WScript.Echo) and properties (e.g.,

WScript.Application, WScript.Fullname) are available immediately without an explicit call to WScript.Application, WScript.Fullname) are available immediately without an explicit call to Cre-ateObject. At callout B, the script uses WScript’s CreateObject method to create a WSH Network  ateObject. At callout B, the script uses WScript’s CreateObject method to create a WSH Network  object. In the string “WScript.Network”, WScript is the application name and Network is the object object. In the string “WScript.Network”, WScript is the application name and Network is the object name. The Set command initializes the objNetwork variable with the object reference that the name. The Set command initializes the objNetwork variable with the object reference that the Cre-ateObject method returns. After you have a valid object reference, you can interact with the object. ateObject method returns. After you have a valid object reference, you can interact with the object.

For example, in callout D, the script echoes the values of the Network object’s For example, in callout D, the script echoes the values of the Network object’s Computer-Name, UserDomain, and UserName properties. As you can see at callout D, you access the object’s Name, UserDomain, and UserName properties. As you can see at callout D, you access the object’s properties using the object reference (objNetwork), followed by a dot (.) and the name of the properties using the object reference (objNetwork), followed by a dot (.) and the name of the property that you want to read. Many properties are read-only, as is the case with the Network  property that you want to read. Many properties are read-only, as is the case with the Network  object’s three properties.

object’s three properties.

Callout C demonstrates how to create a WSH Shell object using VBScript’s CreateObject Callout C demonstrates how to create a WSH Shell object using VBScript’s CreateObject func-tion. Notice the WScript ProgID doesn’t preface CreateObject. Therefore, callout C calls the

tion. Notice the WScript ProgID doesn’t preface CreateObject. Therefore, callout C calls the

VBScript CreateObject function rather than WScript’s CreateObject method. In this case, WScript is VBScript CreateObject function rather than WScript’s CreateObject method. In this case, WScript is the application name, Shell is now the object name, and objShell gets initialized to the object the application name, Shell is now the object name, and objShell gets initialized to the object refer-ence that CreateObject returns.

ence that CreateObject returns.

At callout E, the script invokes the Shell object’s Run method. Similar to how you work with At callout E, the script invokes the Shell object’s Run method. Similar to how you work with the object’s properties, you invoke the object’s methods using the object reference, followed by a the object’s properties, you invoke the object’s methods using the object reference, followed by a dot (.) and the method name and any parameters that the method supports. The script’s comments dot (.) and the method name and any parameters that the method supports. The script’s comments contain details about the different ways to invoke the Run method.

contain details about the different ways to invoke the Run method.

So what are some of the common objects you’ll likely encounter as you venture deeper into So what are some of the common objects you’ll likely encounter as you venture deeper into WSH? Table 1 identifies several common application and object names that you might use with WSH? Table 1 identifies several common application and object names that you might use with CreateObject. As you’ll see next, you can also use GetObject to breathe life into scripts.

CreateObject. As you’ll see next, you can also use GetObject to breathe life into scripts.

12

References

Related documents

To appreciate the methodology, consider first the national annual per-capita gross domestic product (GDP) in constant prices. One could compare an individual born in an era

The solution includes the onboard platforms, the access to an added-value network platform, and an information server located in the customer’s premises that manages

The matters that are absolutely regulated in this special regulation of domestic workers include: 1) Recognition that domestic workers engage in an employment relationship

a) PMT shall prepare the lifting or handling procedures for heavy lifting where types of slings, pads-eyes, weight of the structural assemblies are determined. b) Upon release

Clean Energy program option summaries include narratives and tables. The narrative section provides an overall description of the rationale and objectives of the program option.

To characterize the strain sensors response in a wide range of deformation, four different samples, one for each PEDOT:PSS formulation, are studied with the home- made set up to

beneficial these lords are per stanza : “If the lord of third bhava has attained benefic vargas and is strong, the person born will be virtous; but he will be rash if that planet

If the sprinkler clause for limited combustible cable is included in the 2008 NEC, then intense lobbying will happen with codes officials, such as electrical and fire inspectors,