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

Share Embed Donate


Short Description

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

Description

Guide to  Automating  Administrative Tasks  with

 VBScript Don Baker, Baker, Don Jones, Lary Lar y Lai, Dick Lewis, Mike Otey, John Savill, Bob Wells

Windows & .NET Magazine’s Guide to Automating Administrative Tasks with VBScript  By Don Baker, Don Jones, Larry Lai,  Mike Otey, John Savill, Bob Wells

A Division of Penton Media

Copyright 2002 Windows & .NET Magazine

All rights reserved. No part of this book may be reproduced in any form by an electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without permission in writing from the publisher. It is the reader’s responsibility to ensure procedures and techniques used from this book are accurate and appropriate for the user’s installation. No warranty is implied or expressed.

About the Authors (db aker@ [email protected]) interno sis.com) is is a consulting engineer with Internosis, an e-business consulDon Baker (dbake tancy in Arlington, Virginia. He is an MCSE and an MCP and specializes in Systems Management Server and automated software deployment. Don Jon es (http://www.braincore.net) is a founding partner of BrainCore.Net. He is the author of   Application Center 2000 Configuration and Administration (Hungry Minds). Michael Otey ([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 coauthor of SQL Server 2000 Developer’s Guide (Osborne/McGraw-Hill). John Savill ([email protected]) is a qualified consultant in England and an MCSE. He is the author of The Windows NT and Windows 2000 Answer Book  (Addison Wesley).

(bo bwells@ [email protected] winn etmag.com) m) is a contributing editor for Windows & .NET Magazine. He Bob Wells (bobw is a programming writer at Microsoft, where he is contributing to a new System ystem Adm inistration Scripting Guide that Microsoft will include in its next Windows Server resource kit.

iv

Table of Contents Chap Chapter ter 1: Scripting cripting 101: Dec D eclaring laring and and Initializing Initializing Variable Variables s ...... .......1 VBScript BScript Basics Basics . . . . . . . . . . . . . . . . . . . Declaration and a nd Initializi Initializing ng . . . . . . . . . . . VBScript BScript Directives Directives . . . . . . . . . . . . . VBScript BScript Variables Variables . . . . . . . . . . . . . . Variable Initializati Initialization on . . . . . . . . . . . . Constant on stant Definition Definitionss . . . . . . . . . . . . . Demo.vbs End . . . . . . . . . . . . . . . . . . .

............................... ............................... ............................... .............. ............... .. ............................... ............................... ...............................

....1 ....4 ....4 .... 6 ....6 ....6 ....7

Chap Chapter ter 2: Scripting cripting 101: Working Working with Obje O bjects cts . . . . . . . . . . . . . . . . . . . . . . . 9 Obj Ob jects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Obj Ob jects vs. Utili Utilities ties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 What Is an Ob ject? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Creating Objects O bjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 CreateO bject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 GetOb ject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Chap Chapter ter 3: VB VBS Script cript Tec Tech hniqu niques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Chap Chapter ter 4: Scriptin Scripting g Comm Comman and-L d-Line ine Switch witches es . . . . . . . . . . . . . . . . . . . . . . . . 21 Adding dd ing Flexibili Flexibility ty with Switche Switchess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Hand ling ling Omitted O mitted Switche Switchess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Chap Chapter ter 5: Add Adding ing U sers in Bulk Bulk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Getting Started Started . . . Writing Writing the Script . The Work Begins . Do It with a Script Script

. . . .

........... ........... ........... ...........

. . . .

................. .............. ... ................. .................

. . . .

........... ........... ........... ...........

. . . .

. . . .

....... ....... ....... .......

25 27 29 31

Chapter Chapter 6: 6: VBScript cript to to Generate a Lis Listt of Us U ser Las Last Logon Times Times for a Domain D omain . . 33 Chap Chapter ter 7: VBScript to Datas D atastamp Log Files iles . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Chap Chapter ter 8: Simplify implify Win2K Wi n2K D esktop ktop Deploym Deploymen entt . . . . . . . . . . . . . . . . . . . . . . 37 The Deployme De ployme nt Environm Environmen entt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Create a Hard Disk Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Write Write a FinalSetup FinalSetup .vbs Script Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Prepare the Disk Disk Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Unattend ed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 GuiUnattende GuiUnattended d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 GuiRun GuiRunOn Once ce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 UserData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Identif Iden tificati ication on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Clone the Master Image to a Workstation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

1

Chapter 1

Scripting 101: Declaring and Initializing Variables By Bob Wells  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 initialization section in detail. Before we start, you need to know some VBScript basics to ease your transition to Windows Script Host (WSH).

VBScript Basics 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 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 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 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) require you to be case-conscious. You also need to be case-conscious when you use Active Directory 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 specify NetWare 3.x). You must key ADSI namespace identifiers according to the ADSI specification, 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 available at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netdir/ad/  using_active_directory.asp. 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 comments 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  Listing isting 1, go to http:// www .winnetmag.com/ files/ iles/ 5505 5505// 5505 5505.zi .zip.) p.) 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 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 lines into multiple short lines can improve the readability of a script. In VBScript, you can use the line-continuation marker to let a statement or line of code span multiple lines. I often use the linecontinuation marker when I initialize dynamic arrays (e.g., at callout A in Listing 1) or to pass a

2

Guide to VBScripting

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 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 multiple statements. In VBScript, you can use a colon (:) to separate multiple statements within a line of code. In the code line 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 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 character. Pressing Enter automatically inserts the new-line character. VBScript doesn’t use the visible line terminator (;) that JScript and Perl use. The seventh and final ground rule I want to establish governs VBScript identifiers (e.g., variables, 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.

Listing 1  Demo.vbs ’ * ‘ demo.vbs ‘ * ‘ Declaration and Initialization Section ‘ * Rem *** Script Directives *** Option Explicit On Error Resume Next Rem Dim Dim Dim

*** Variable Declarations *** objFileSystem, objShell, objLogFile, objTempFile arrStrings, intReturnCode strBuffer, strLogFile, strTempFile

Rem *** Constant Definitions *** Const OpenFileForReading = 1 Rem *** Variable Initialization *** intReturnCode = 0 strBuffer = “” strL strLog ogFi File le = “c: “c:\” \” & Spl Split it(W (WSc Scri ript pt.S .Scr crip iptN tNam ame, e, “.”) “.”)(0 (0) ) & “.lo “.log” g” strTempFile = “c:\temp.txt” arrSt rString ings = Array ray(“ab “abcdef defghij hijklmn lmnopq opqrstu stuvwxy wxyz”, _ “ABCDEFGHIJKLMNOPQRSTUVWXYZ”, _ “the quick brown fox jumps over the lazy dogs back”) ‘ Script Body Section ‘ * ‘ Using If-Then-End If to demonstrate the On Error Resume Next statement. If Err.Number Then WScript.Echo “Bob’s Friendly Error Message” & vbNewLine & _ “Error Number: “ & Err.Number & vbNewLine & _ “Error Description: “ & Err.Description Err.Clear End If

A

B

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

Continued 

Chapter Chapter 1 Scripti ng 101: Declaring and and Initializi Initi alizing ng Variables 3

Listing 1: continued  Set objFileSystem = CreateObject(“Scripting.FileSystemObject”) Set objLogFile = objFileSystem.CreateTextFile(strLogFile, TRUE) objLogFile.WriteLine(Now & “:” & vbTab & WScript.ScriptFullName & “ Started.”) ‘ Create WSH Shell object. ‘ Run external command redirecting commands output to temporary file. ‘ Check for error condition and write appropriate message to log file. Set objShell = WScript.CreateObject(“WScript.Shell”) intReturnCode = objShell.Run(“cmd /C ipconfig.exe >” & strTempFile, 0, TRUE) If Err.Number Then objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) Err.Clear Else objLogFile.WriteLine(Now & “:” & vbTab & “Run completed successfully.”) End If ‘ 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. ‘ Check for error and write appropriate message to log file. ‘ Close TextStream object. Set objTempFile = objFileSystem.OpenTextFile(strTempFile, OpenFileForReading) strBuffer = objTempFile.ReadAll If Err.Number Then objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) Err.Clear Else objLogFile.WriteLine(Now & “:” & vbTab & “Open and read “ & strTempFile & _ “ completed successfully.”) End If objTempFile.Close ‘ Display the buffer contents that are the redirected result of the run ‘ command. WScript.Echo strBuffer ‘ Delete c:\temp.txt file. ‘ Check for error and write appropriate message to log file. objFileSystem.DeleteFile(strTempFile) If Err.Number Then objLogFile.WriteLine(Now & “:” & vbTab & Err.Number & “: “ & Err.Description) Err.Clear Else objLogFile.WriteLine(Now & “:” & vbTab & “Delete “ & strTempFile & _ “ completed successfully.”) End If ‘ Write closing line to log file and close log file. objLogFile.WriteLine(Now & “:” & vbTab & WScript.ScriptFullName & “ Finished.”) objLogFile.Close ‘ Create TextStream object to read in log file. ‘ Read entire file into buffer using the TextStream objects ReadAll method. ‘ Close TextStream object. Set objLogFile = objFileSystem.OpenTextFile(strLogFile, OpenFileForReading) strBuffer = objLogFile.ReadAll objLogFile.Close ‘ Display the buffer’s content, which is the log file in this case. WScript.Echo strBuffer ‘ Delete the log file, release object references, and exit script. objFileSystem.DeleteFile(strLogFile) Set objShell = Nothing Set objFileSystem = Nothing WScript.Quit(0) ‘ * ‘ * demo.vbs end

4

Guide to VBScripting

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

VBScript Directives  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 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 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 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 error occurs whenever the VBScript interpreter encounters an undefined variable during script execution. Using Option Explicit helps you isolate typographical mistakes and variables with incorrect scopes (a scope defines the visibility of a variable to other parts of the script such as functions and subroutines). The On Error Resume Next statement controls how a script notifies you when a script encounters 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 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 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 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. 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  demo.vbs: Rem Dim arrStrings, intReturnCode

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 console; instead, the script will produce Figure 2’s custom error dialog box, which states that a script variable is undefined. The  If-Then-End If  statement at callout B in Listing 1 acts as a rudimentary 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 continues 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 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

Chapter Chapter 1 Scripti ng 101: Declaring and and Initializi Initi alizing ng Variables 5

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 Description property. Figure 1 not only includes the name of the undefined variable, it also provides the specific line number for the error. In Figure 2, the error description simply states that the script tried to use an undefined variable.)

Figure 1  Example WSH Script Execution Error dialog box

Figure 2  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 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 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. However, a better way to fix the problem is to define the undeclared variable (in this case, remove the Rem from the declaration statement): Dim arrStrings, intReturnCode

6

Guide to VBScripting

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

VBScript Variables  Earlier, I said declaring variables in VBScript is optional—and it is. However, engaging in the exercise 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 consider the environment and objects with which your script interacts, which can result in betterdesigned scripts that do what you intend them to do. 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 name is the mechanism through which you assign a value to a variable. Declaring VBScript variables 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 declarations follow the script directives at the beginning of the script. VBScript supports one primary data type: variant. You 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 information as you do in VB. Instead, VBScript determines a variable’s type at runtime, based on the variable’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 more information about VBScript variables, download the free VBScript HTML Help file (vbsdoc.exe) at http://msdn.microsoft.com/scripting/vbscript/download/vbsdoc.exe.

Variable Initialization  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 body. You can initialize a variable to one value, such as a number or a string, or to a more complex value constructed from multiple elements. For example, in the variable initialization section of demo.vbs, the script assigns to strLogFile the co ncatenation ncate nation (from (from VBS VBScript’s cript’s & op erator) o f three three substri sub strings. ngs. The first sub substring string (“c:\ (“c:\ ”) and 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 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 returns. The end result is a log file name that is identical to the script name without the extension.

Constant Definitions  Constants are named values that don’t change throughout the execution of a script. VBScript supports two types of constants: literal and intrinsic. Literal 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

Chapter Chapter 1 Scripti ng 101: Declaring and Initiali Init ializing zing Variables 7

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 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 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 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 other constants or expressions. 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 constants 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 Reference and the Scripting Run-Time Reference in the VBScript Help file provide a complete list of  constants. 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 release of WSH. In the interim, if you want to use constants that other objects define, simply duplicate 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 OpenFileForReading constant.

Demo.vbs End 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, 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 Chapter 2, I’ll examine one of the more important elements generally found in the body of a script: object handling.

9

Chapter 2

Scripting 101: Working with Objects By Bob Wells  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 perform in the script body: working with objects.

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, 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) background, quite the opposite is true for individuals with only a batch file background.

Objects vs. Utilities 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 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. Unfortunately, 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 void. Sound familiar? 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 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 scripting-challenged (especially compared to UNIX). In fact, the limited functionality led to a proliferation 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 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  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 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 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 with and control COM-enabled services and applications.

10

Guide to VBScripting

Figure 1  How NT’s graphical applications and utilities call Win32 APIs to run the task that the application or utility performs Server Manager

Scripts C:\>utilities

User Manager

OK 

Win32 API

Event Log

Registry

Service Control Manager

SAM

System Data

Performance Data

Figure 2 COM exposing system services MMC MMC Active Directory Snap-In

C:\>utilities

Batch Files

OK 

WSH Scripts

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

Event Log

Registry

 Active Directory

SAM

Service Control Manager

System and Performance Data

For example, in addition to abstracting multiple and disparate directory services, Active Directory 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

Chapter Chapter 2 Scripti ng 101: Working Worki ng with wi th Objects

11

(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 WebBased 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 understand what an object is.

What Is an Object? An object is simply a thing. Each object has a set of characteristics or attributes that describe the object and the actions it performs. Network OSs, messaging systems, applications, and programming languages generally classify objects in terms of a user, a group, a computer, a printer, a network, or an application. These entities are all objects in the IT world. Each of these objects has a set of  properties  properties that uniquely describe it. Each object might also perform an action using its methods. So in the computer world, properties describe an object, and objects use methods to perform actions. 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 user object before you can interact with it, so let’s take a look at how to create objects.

Creating 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 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, environment variables, and the registry. 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 methods—CreateOb ject and GetObject—that you can use to create objects. Using these methods is a concept that represents a radical departure from calling utilities inside of batch files. 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 an additional layer of work and is slightly less efficient than using the analogous VBScript functions. WScript includes these methods to support third-party script engines that might not provide a mechanism to create objects. 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. 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 an explicit call to CreateObject. 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 place to start is with syntax and definitions.

12

Guide to VBScripting

CreateObject  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 Set objReference = CreateObject(“strApp.strObj” [, “strServerName”])

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 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, strServerName 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 WSH and VBScript releases. CreateObject returns a reference to the newly created object. Typically, you assign the reference to an object variable so that you can interact with the object within your script. In the previous 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 methods and read or set the object’s properties. The objects.vbs example script in Listing 1 demonstrates 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., WScript.Application, WScript.Fullname) are available immediately without an explicit call to CreateObject. 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 name. The Set command initializes the objNetwork variable with the object reference that the CreateObject 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 ComputerName, 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 property that you want to read. Many properties are read-only, as is the case with the Network  object’s three properties. Callout C demonstrates how to create a WSH Shell object using VBScript’s CreateObject function. 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 the application name, Shell is now the object name, and objShell gets initialized to the object reference that CreateObject returns. 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 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. 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 CreateObject. As you’ll see next, you can also use GetObject to breathe life into scripts.

Chapter Chapter 2 Scripti ng 101: Working Worki ng with wi th Objects

LISTING 1: Objects.vbs Option Explicit Dim objNetwork, objShell, intRC ‘ Constants that the Shell Object’s Run method uses. Const vbHide = 0 Const vbNormalFocus = 1 Const vbMinimizedFocus = 2 Const vbMaximizedFocus = 3 Const vbNormalNoFocus = 4 Const vbMinimizedNoFocus = 6 ‘ ‘ ‘ ‘

* * * *

Every WSH script automatically creates a WScript object. You can immediately invoke WScript methods and read WScript properties as WScript’s Echo method and numerous properties demonstrate.

WScript.Echo “WScript Properties” & vbNewLine & _ “________" & vbNewLine & _ “Application: “ & WScript.Application & vbNewLine & _ “Fullname: “ & WScript.Fullname & vbNewLine & _ “Interactive: “ & WScript.Interactive & vbNewLine & _ “Name: “ & WScript.Name & vbNewLine & _ “Path: “ & WScript.Path & vbNewLine & _ “ScriptFullName: “ & WScript.ScriptFullName & vbNewLine & _ “ScriptName: “ & WScript.ScriptName & vbNewLine & _ “Version: “ & WScript.Version & vbNewLine

A

‘ * To interact with other objects, you must first create a reference ‘ * to the target object. Here I use WScript’s CreateObject method. Set objNetwork = WScript.CreateObject(“WScript.Network”) ‘ ^^^^^^^^^^ ^^^^^^^.^^^^^^^ ‘ The object reference variable is first followed by strApp.strObj.

B

‘ * Here I use the more efficient VBScript CreateObject function. Set objShell = CreateObject(“WScript.Shell”)

C

‘ * After you have a valid object reference, you access the object’s ‘ * properties using the objRef.PropertyName syntax. WScript.Echo “Properties of the Network Object (read-only)” & _ vbNewLine & “__________________” & vbNewLine & _ “ComputerName: “ & objNetwork.ComputerName & vbNewLine & _ “UserDomain: “ & objNetwork.UserDomain & vbNewLine & _ “UserName: “ & objNetwork.UserName ‘ * You invoke the objects methods using the ‘ * objRef.MethodName([Parameter List]) syntax. objShell.Run “notepad.exe”, vbMaximizedFocus, FALSE intRC = objShell.Run(“wordpad.exe”, vbMinimizedFocus, FALSE) ‘ ‘ ‘ ‘ ‘ ‘

* * * * * *

‘ * ‘ * Set Set

Notice the difference between the two invocations of the Shell’s Run method. The first invocation doesn’t enclose the parameter list in parentheses. The second invocation encloses the parameter list. The rule is that when using a method as an RValue (appearing on the right-hand side of an assignment statement), you can enclose the parameter list in parentheses; otherwise you can’t. When you’re done with an object, you release the reference using VBScript’s Nothing keyword. objNetwork = Nothing ObjShell = Nothing

D

E

13

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF