1. Trang chủ
  2. » Giáo Dục - Đào Tạo

vbscript, wmi and adsi unleashed using vbsscript, wmi, and adsi to automate windows administration

574 1,1K 0
Tài liệu đã được kiểm tra trùng lặp

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề VBScript, WMI and ADSI Unleashed Using VBScript, WMI, and ADSI to Automate Windows Administration
Tác giả Don Jones
Người hướng dẫn Karen Gettman, Editor-in-Chief, Joan Murray, Acquisitions Editor, Gina Kanouse, Managing Editor, Kristy Hart, Senior Project Editor, Karen Annett, Copy Editor, Williams Woods Publishing, LLC, Proofreader, Gary Adair, Cover Designer, Bronkella Publishing, Composition
Trường học Sams Publishing
Chuyên ngành Windows Administration and Scripting
Thể loại Book
Năm xuất bản 2007
Thành phố Indianapolis
Định dạng
Số trang 574
Dung lượng 5,44 MB

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

Nội dung

.1 Part I Introduction to Windows Administrative Scripting 1 Scripting Concepts and Terminology.. .9 Part I Introduction to Windows Administrative Scripting 1 Scripting Concepts and Term

Trang 2

U N L E A S H E D

800 East 96th Street, Indianapolis, Indiana 46240 USA

Don Jones

Using VBScript, WMI, and ADSI to

Trang 3

VBScript, WMI, and ADSI Unleashed

Copyright © 2007 by Sams Publishing

All rights reserved No part of this book shall be reproduced, stored in a retrieval system, or

trans-mitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written

permission from the publisher No patent liability is assumed with respect to the use of the

infor-mation contained herein Although every precaution has been taken in the preparation of this

book, the publisher and author assume no responsibility for errors or omissions Nor is any

liabil-ity assumed for damages resulting from the use of the information contained herein.

This material may be distributed only subject to the terms and conditions set forth in the Open

Publication License, v1.0 or later (the latest version is presently available at

1971-VBScript, WMI and ADSI unleashed : using VBSscript, WMI, and ADSI to automate Windows

administration / Don Jones — 1st ed.

p cm.

ISBN 0-321-50171-3 (pbk : alk paper) 1 VBScript (Computer program language) 2 Microsoft

Windows (Computer file) 3 Directory services (Computer network technology) I Title

QA76.73.V27J67 2007

005.13’3—dc22

2007008741 Printed in the United States on America

First Printing May 2007

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been

appro-priately capitalized Sams Publishing cannot attest to the accuracy of this information Use of a term

in this book should not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as possible, but no

warranty or fitness is implied The information provided is on an “as is” basis The author and the

publisher shall have neither liability nor responsibility to any person or entity with respect to any

loss or damages arising from the information contained in this book.

Bulk Sales

Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk

purchases or special sales For more information, please contact

U.S Corporate and Government Sales

Copy EditorKaren AnnettIndexerBrad HerrimanProofreaderWilliams WoodsPublishing, LLCCover DesignerGary AdairCompositionBronkella Publishing

Trang 4

Contents at a Glance

Introduction .1

Part I Introduction to Windows Administrative Scripting 1 Scripting Concepts and Terminology .13

2 Running Scripts .21

3 The Components of a Script .39

4 Designing a Script .55

Part II VBScript Tutorial 5 Functions, Objects, Variables, and More .75

6 Input and Output .101

7 Manipulating Numbers .115

8 Manipulating Strings .129

9 Manipulating Other Types of Data .145

10 Controlling the Flow of Execution .155

11 Built-In Scripting Objects .173

12 Working with the File System .193

13 Putting It All Together: Creating Your First Script from Scratch .219

Part III Windows Management Instrumentation and Active Directory Services Interface 14 Working with ADSI Providers .247

15 Manipulating Domains .257

16 Manipulating Users and Groups .271

17 Understanding WMI .283

18 Querying Basic WMI Information .299

19 Querying Complex WMI Information .317

20 Putting It All Together: Your First WMI/ADSI Script .335

21 Testing and Debugging WMI and ADSI Queries .357

Part IV Advanced Scripting Techniques 22 Modular Script Programming .373

Trang 5

24 Scripting Security .399

25 Introduction to HTML Applications .409

26 Debugging Tips, Tools, and Techniques .421

Part V Ready-to-Run Examples 27 Logon and Logoff Scripts .439

28 Windows and Domain Administration Scripts .455

29 Network Administration Scripts .481

30 WMI and ADSI Scripts .497

Appendix .509

Index .523

Trang 6

Table of Contents

Who Should Read This Book? .2

How to Use This Book .2

Part I: Introduction to Windows Administrative Scripting .3

Part II: VBScript Tutorial .3

Part III: Windows Management Instrumentation and Active Directory Services Interface .5

Part IV: Advanced Scripting Techniques .6

Part V: Ready-to-Run Examples .7

Appendix .8

Preparing to Use This Book .8

Typographical Elements .8

Sample Scripts .9

Sample Scripts—Explained .9

Part I Introduction to Windows Administrative Scripting 1 Scripting Concepts and Terminology 13 Overview of Scripting .13

Script Hosts .14

ActiveX Scripting Languages .16

The Component Object Model (COM) .18

Critical Scripting Security Issues .18

VBScript Versus Windows PowerShell .19

Summary .20

2 Running Scripts 21 Windows Script Host .21

Command-Line Scripts .23

Notepad and Script Editors .25

Bare Bones: Notepad .26

A Step Up: Programmer’s File Editor .26

Script-Specific: VBScript Editors .27

All-Inclusive: VBScript IDEs .29

Trang 7

Writing Your First Script .33

Running Your First Script .35

Debugging Your First Script .35

Summary .37

3 The Components of a Script 39 A Typical VBScript .39

Functions .42

Subroutines .43

Main Script .44

Using Custom Functions and Subroutines .45

Using Intrinsic Functions and Statements .47

Making Decisions in a Script .48

Comments and Documentation .48

Summary .53

4 Designing a Script 55 Creating a Task List .56

Selecting the Appropriate Tools .58

Displaying a Message .59

Mapping a Drive .60

Checking Group Membership .61

Mapping a Printer .61

Getting the Local IP Address .61

Getting the Third Octet from the IP Address .63

All Tasks Accounted For .63

Creating Modules to Perform Tasks .63

Validating User Input .69

Planning for Errors .70

Creating Script Libraries .72

Summary .72

Part II VBScript Tutorial 5 Functions, Objects, Variables, and More 75 Variables Defined .76

Declaring Variables .79

Understanding Data Types .82

Assigning Data to Variables .82

Data Coercion .83 VBScript, WMI, and ADSI Unleashed

Trang 8

Functions Defined .85

Input Parameters .85

Output Values .87

Intrinsic Versus Custom Functions .88

Statements and Subroutines Defined .92

Functions, Without the Output .92

Objects Defined .94

Properties .95

Methods .95

Collections .96

A Sample Object .97

Scripting with Objects .98

Summary .99

6 Input and Output 101 Displaying Messages .101

TheMsgBoxStatement and Function .102

More Complex Messages .105

MsgBox Best Practices .106

Go Generic with WScript.Echo .107

Asking for Input .108

Graphical Input .108

Command-Line Input .109

Command-Line Parameters as Input .110

Running Command-Line Scripts .111

Parsing Parameters .111

Summary .114

7 Manipulating Numbers 115 Numbers in VBScript .115

Basic Arithmetic .116

Advanced Arithmetic .118

Boolean Math .121

Converting Numeric Data Types .126

Converting Other Data Types to Numeric Data .127

Summary .127

8 Manipulating Strings 129 Strings in VBScript .129

Working with Substrings .131

Contents

Trang 9

Concatenating Strings .135

Changing Strings .139

Formatting Strings .141

Converting Other Data Types to String Data .142

Summary .143

9 Manipulating Other Types of Data 145 Working with Dates and Times .145

Dates and Times in VBScript .145

Getting the Date or Time .146

Converting Date and Time Data .147

Working with Past and Future Dates .147

Working with Arrays .148

Arrays in VBScript .149

Creating and Manipulating Arrays .149

Working with Array Data .151

Working with Bytes .152

Bytes in VBScript .152

Converting Byte Data .152

Summary .153

10 Controlling the Flow of Execution 155 Conditional Execution .155

If/Then .156

Select/Case .161

Loops .162

Do While/LoopandDo/Loop While .162

Do Until/LoopandDo/Loop Until .163

For/Next .164

For Each/Next .165

Exiting Loops .166

Putting It All Together .167

Summary .170

11 Built-In Scripting Objects 173 TheWScriptObject .173

TheNetworkObject .174

Methods and Properties .175

Practical Application .178

TheADSystemInfoObject .179 VBScript, WMI, and ADSI Unleashed

Trang 10

TheShellObject .180

Methods and Properties .180

TheShortcutObject .187

Methods and Properties .187

Practical Application .188

Objects in Detail .189

Summary .191

12 Working with the File System 193 TheFileSystemObjectLibrary .193

Working with Drives .194

Working with DriveObjects .195

Working with Folders .197

Working with FolderObjects .198

Folder Attributes .200

Properties That Are Objects .202

Working with Files .203

Working with FileObjects .204

Reading and Writing Text Files .206

Other FSO Methods and Properties .209

Creating a Log File Scanner .211

Summary .218

13 Putting It All Together: Creating Your First Script from Scratch 219 Designing the Script .219

Gathering Facts .220

Defining Tasks .221

Outlining the Script .222

Writing Functions and Subroutines .223

Identifying Candidate Modules .223

Writing the Filename Formatting Function .223

Writing the Main Script .228

Identifying Potential Errors .231

Testing the Script .234

Analyzing the Results .236

Adding Debug Code .236

Modifying the Script .240

Completing the Script .241

Summary .244

Contents

Trang 11

Part III Windows Management Instrumentation and Active Directory Services

Interface

Using ADSI Objects .247

Using the WinNT Provider .249

WinNT Examples .250

Using the LDAP Provider .252

Other Providers .254

Summary .255

15 Manipulating Domains 257 Querying Domain Information .257

Changing Domain Settings .259

Working with OUs .260

Creating an OU .260

Modifying an OU .261

Querying an OU .263

Deleting an OU .263

Putting It All Together .264

Summary .269

16 Manipulating Users and Groups 271 Creating Users and Groups .271

The WinNT Way .272

The LDAP Way .273

Querying User Information .273

Changing User Settings .274

Working with Groups .275

Putting It All Together .277

Summary .281

17 Understanding WMI 283 The WMI Hierarchy .283

Providers and Consumers .285

WMI Versions .286

Exploring WMI’s Capabilities .286

WQL Queries .289

Installing WMI .290 VBScript, WMI, and ADSI Unleashed

Trang 12

Using the WMI Tools .291

Scriptomatic .292

The Easy Way to Write WMI Scripts .293

Find the Class .293

Write the Query, Test the Query .294

Write the Script .295

Test the Script .297

Summary .297

18 Querying Basic WMI Information 299 The WMI Query Language (WQL) .299

WMI Query Basics .300

Boolean Operators .301

Comparison Operators .302

Associators, References, and Keys .303

Determining What to Query .304

Testing the Query .306

Writing the Query in VBScript .308

Using the Query Results .312

Alternative Methods .314

Summary .316

19 Querying Complex WMI Information 317 Understanding WMI Relationships .317

Associating WMI Instances .321

ASSOCIATORS OF .321

REFERENCES OF .323

UsingWHEREwithASSOCIATIONS OFandREFERENCES OF .324

Writing the Query .325

Testing the Query .325

Writing the Query in VBScript .326

Another Example .330

Summary .333

20 Putting It All Together: Your First WMI/ADSI Script 335 Designing the Script .335

Writing Functions and Subroutines .340

Writing the Main Script .343

Testing the Script .351

Summary .355

Contents

Trang 13

21 Testing and Debugging WMI and ADSI Queries 357

Debugging Outside the Script .358

Debugging WMI Queries .358

Debugging ADSI Queries .366

Summary .370

Part IV Advanced Scripting Techniques 22 Modular Script Programming 373 Looking for Modules .373

When Do You Modularize? .377

The Downside of Copy-and-Paste .377

Introduction to Windows Script Components .378

Scripting and XML .378

Summary .388

23 Scripts Packaging and Protection 389 Installing the Script Encoder .390

Writing Encoded Scripts .390

Running Encoded Scripts .393

Encoding: The Downside .394

Script Packaging .394

Summary .397

24 Scripting Security 399 Why Scripting Can Be Dangerous .399

Security Improvements in Windows XP and Windows Server 2003 .400

Digitally Signing Scripts .402

Running Only Signed Scripts .404

Ways to Implement Safe Scripting .405

The Filename Extension Game .405

Deleting the Files .405

Script Signing .405

Implementing TrustPolicy .406

Antivirus Software .406

Defunct Techniques .406

Summary .407

25 Introduction to HTML Applications 409 Event-Driven Scripting .410

VBScript, WMI, and ADSI Unleashed

Trang 14

HTA Differences .411

Steps for Writing an HTA .411

Writing the Functional Code First .411

Designing the User Interface .412

Converting the HTML Code .414

Adding Code .416

Wiring Up Events .418

Summary .420

26 Debugging Tips, Tools, and Techniques 421 Types of Bugs .421

Preventing Syntax Errors .422

Use a VBScript Editor—and Pay Attention! .422

Use Option Explicit .423

Reuse Your Code .424

Debugging Logic Errors .425

Do Not Spaghetti-Debug! .425

Break It Down .427

Get Inside the Script .428

Get Out of the Script .432

What About a Debugger? .434

Summary .435

Part V Ready-to-Run Examples 27 Logon and Logoff Scripts 439 NT and Active Directory Logon Scripts .440

Active Directory–Specific Logon Scripts .446

Active Directory Logoff Scripts .451

Summary .453

28 Windows and Domain Administration Scripts 455 Automating User Creation .455

Finding Inactive Users .464

Collecting System Information .469

Templates .474

Summary .480

29 Network Administration Scripts 481 Shutting Down Remote Computers .481

Contents

Trang 15

Finding Out Who Has a File Open .486

Uninstalling Remote MSI Packages .489

Listing Hot Fixes and Software .492

Summary .495

30 WMI and ADSI Scripts 497 The All-Purpose WMI Query Script .497

The All-Purpose WMI Update Script .499

The All-Purpose ADSI Object Creation Script .500

The All-Purpose ADSI Object Query Script .502

The All-Purpose ADSI Object Deletion Script .502

Mass Password Changes with ADSI .503

Updating Service Accounts .505

Summary .508

Index 523

VBScript, WMI, and ADSI Unleashed

Trang 16

About the Author

Don Jonesis an internationally recognized scripting guru, speaker, and author He serves

as the Director of Projects and Services for SAPIEN Technologies, where his primary job is

to drive the development of new products and services for Windows administrative ing Don is the founder of ScriptingAnswers.com, the web’s friendliest community forWindows scripting Don has written more than 30 books on information technology,

script-including Managing Windows with VBScript and WMI (Addison-Wesley; the first edition of this book), Windows Administrator’s Automation Toolkit (Microsoft Press), Advanced VBScript

for Windows Administrators (Microsoft Press), and Windows PowerShell: TFM™ (SAPIEN

Press) Don heads SAPIEN Technologies’ Las Vegas office, speaks at a half-dozen technical

conferences each year, and contributes monthly content to Microsoft TechNet Magazine.

Trang 17

I would also like to thank my technical review panel made up of Dan Cazzulino, JimChristopher, Doug Ellis, Jeffery Hicks, Bob Reselman, and Rob van der Woude Withouttheir valuable commentary and feedback, the book would not have been what it is today.Support on the home front is important, too: Thanks to Chris for being wonderfullypatient, and thanks to Alex, Ferdinand, Spoon, and Margaret for giving me the time towork on this lengthy revision Thanks also to my ferrets, Pepper, Patch, and Nutmeg, whowere wonderfully understanding—not—when “daddy” couldn’t play right then because

he was typing

And thanks, perhaps most of all, to Microsoft, for realizing at long last how importantVBScript is to the community of Windows administrators, for deciding to continue toinclude it in future versions of Windows, and for giving the TechNet “Scripting Guys”full-time permission to produce samples, answer questions, and, in general, really

promote administrative scripting to the world

Don Jones

SAPIEN Technologies

May 2007

Trang 18

We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator We value

your opinion and want to know what we’re doing right, what we could do better, whatareas you’d like to see us publish in, and any other words of wisdom you’re willing topass our way

You can email or write me directly to let me know what you did or didn’t like about thisbook—as well as what we can do to make our books stronger

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book’s title and author as well as yourname and phone or email address I will carefully review your comments and share themwith the author and editors who worked on the book

Trang 19

conven-This page intentionally left blank

Trang 20

Microsoft introduced Visual Basic, Scripting Edition—commonly known as VBScript—inthe mid-1990s, positioning it as a native replacement for Windows’ aging command-linebatch language, which was based on Microsoft’s earliest operating system, MS-DOS.VBScript was intended to be easy to learn, powerful, and flexible The language wasincluded as an add-on to Windows 95 and Windows NT 4.0, was an optional installationcomponent included in Windows 98, and was included in all editions of Windows Me,Windows 2000, Windows XP, and Windows Server 2003

Software developers immediately seized upon VBScript for web programming, particularly

in Active Server Pages, Microsoft’s rapid-development programming framework for theweb However, Windows administrators—one of VBScript’s initial target audiences—wereleft cold VBScript seemed to be much more complicated than administrators’ belovedMS-DOS-based batch language, and many didn’t see the need to learn an entirely newbatch language

When Windows 2000 and Active Directory came along, however, administrators foundthat Windows administration had become a great deal more complex Suddenly, adminis-trators were searching for Resource Kits and other utilities that offered automated admin-istration, especially for repetitive tasks Active Directory enabled the use of VBScript forlogon and logoff scripts, which seemed to promise more advanced-use environmentmanipulation At around the same time, Microsoft’s naiveté in releasing a powerfullanguage like VBScript with absolutely no security controls resulted in a huge wave ofhigh-impact VBScript-based viruses, forcing administrators to lock down their environ-ments and remove VBScript as an option both for viruses and for administrative tools

As a regular speaker at some of the country’s top technical conferences that focus onWindows technologies, including TechMentor, the past few years I’ve given half- and full-day sessions on VBScripting for Windows administrators, and the sessions have beenincredibly popular In these sessions, I try to provide just enough VBScript experience tomake scripting possible, and then concentrate on accomplishing common administrativetasks with VBScript I also cover the security concerns of VBScript and provide administra-tors with the means for safely using VBScript in their environments This book is essen-tially a written form of those sessions, greatly expanded with more coverage of WindowsManagement Instrumentation and other advanced topics, and with more coverage ofVBScript security issues and resolutions

I’m not out to turn you into a programmer In fact, one of the real successes of VBScript is

that you don’t need to be a programmer to use it Most of what you’ll be doing in this

book involves using VBScript to tell Windows to do things for you; you’ll be able toignore much of VBScript’s complexity, using it as a sort of electronic glue to combinevarious operating system functions

Trang 21

VBScript, WMI, and ADSI Unleashed

It’s been four years since the original edition of this book, published as Managing Windows

with VBScript and WMI At the time, Windows administrators were really just discovering

scripting and its potential to automate administrative tasks; since then, scripting andautomation have taken off in a big way Managers—not just administrators—realize thatautomation makes better use of skilled technical professionals, freeing them up from

boring, repetitive tasks for new projects That realization has led to the word scripting

being added to many a high-end job description, and scripting is emerging as one

of the most important differentiators between entry-level technicians and experiencedprofessionals

In the past four years, I’ve done a tremendous amount of work to promote scripting andeducation I produced more than a dozen free Webcasts for Microsoft TechNet (which are still viewable; links can be found on http://www.ScriptingAnswers.com), launched

a web community for administrative scripting called www.ScriptingAnswers.com,

created two complete series of training videos for scripting (viewable at

http://www.ScriptingTraining.com), designed a web search engine specifically for scriptingresources (http://www.SearchScripting.com), and wrote nearly a half-dozen books onWindows scripting and automation (including two free ones from

http://www.Realtimepublishers.com) Scripting is here to stay

Who Should Read This Book?

The only assumption I have about you is that you already know how to administer someversion of Microsoft Windows You’ll find that most of the material in this book is suit-able for Windows NT, Windows 2000, Windows Server 2003, and (as it’s known as of thiswriting) Windows “Longhorn” Server environments (that includes the client versions ofthese operating systems, such as Windows XP and Windows Vista), and it will continue to

be useful through future versions of Windows I do not assume that you have any ground in programming, and I’m not going to give you a programming background.You should have a desire to learn how to use what I call “the batch language of thetwenty-first century” and a desire to move away from clumsier—and often more

back-complex—batch files based on the MS-DOS batch language Although some folks like torefer to batch files as scripts, I don’t; and when you see how easy and flexible VBScript is,you’ll understand why!

How to Use This Book

You can read this book in order from the Introduction to the Appendix However, if youalready have some experience with VBScript, or if you just want to dive right in to themore complete sample scripts, you can skip around as much as you want This book isorganized in the same way that I organize my live VBScripting sessions at conferences, soyou might feel that it’s some time before you really get into the meat of scripting I assureyou, though, that each example in this book—starting in Chapter 1—is focused onWindows administration You’ll get your feet wet right away!

Trang 22

To help you decide where to start, the following sections provide a brief overview of eachchapter

Part I: Introduction to Windows Administrative Scripting

Part I serves as an introduction to the world of scripting and provides you with a ology for approaching administrative tasks from a scripting standpoint One of the mostdifficult parts about producing new scripts from scratch is the “Where do I start?” factor,and this part provides you with a framework for figuring that out every time

method-Chapter 1: Scripting Concepts and Terminology

As implied previously, administrative scripting isn’t hard-core programming Instead, it’susing VBScript as a sort of electronic glue to secure various bits of the Windows operatingsystem together This chapter introduces you to those various bits and sets the stage withsome basic terminology that you’ll use throughout this book

Chapter 2: Running Scripts

Writing a script isn’t much fun if you can’t run the script! This chapter focuses on thetechnologies used to execute scripts You might be surprised to learn how many differentMicrosoft products support scripting This chapter shows you how far your scripting skillscan really take you and also introduces you to some scripting tools that can make writingand debugging scripts a bit easier

Chapter 3: The Components of a Script

This chapter presents a complete administrative script and then breaks it down line to explain its various components Although this chapter isn’t necessary to learningadministrative scripting, it will help you write scripts that are more reliable and easier totroubleshoot

line-by-Chapter 4: Designing a Script

As mentioned previously, one of the toughest aspects about scripting can be figuring outwhere to start This chapter provides you with a framework that you can use as a startingpoint for every new scripting project This chapter also introduces you to some conceptsthat many scripting books ignore, such as planning for errors and creating a useful

“resource kit” of script components that you can reuse throughout your scripting projects

Part II: VBScript Tutorial

Part II serves as your official crash course to the VBScript language: just enough to makeadministration via script a possibility! The best part is that this part doesn’t use the trite

“Hello, world” examples that books for software developers often start out with Instead,every example is useful to you as a Windows administrator This means you’ll producesimple, useful scripts at the same time you’re learning VBScript What could be better?

Trang 23

Chapter 5: Functions, Objects, Variables, and More

This chapter shows you the basic building blocks of any script and introduces you tosome sample scripts that use each building block in a particular administrative task This

is really the meat of administrative scripting, and you’ll be able to write useful scriptswhen you’re finished with this chapter

Chapter 6: Input and Output

You can make your scripts more flexible by adding the ability to dynamically changecomputer, user, and domain names, along with other information This chapter showsyou how your script can collect information it needs to run and dynamically alter itself totake advantage of that information

Chapter 7: Manipulating Numbers

This chapter explains how scripts can manipulate numbers, making it easier to createscripts that work with numeric data, such as user account data It also introduces you toVBScript’s numeric data handling and conversion commands, putting you on the path tosome great scripting techniques

Chapter 8: Manipulating Strings

Strings—a fancy word for text data—are at the heart of most scripting tasks This chaptershows you how VBScript deals with strings and how you can easily integrate them intoyour scripts

Chapter 9: Manipulating Other Types of Data

Aside from text and numbers, your scripts might need to deal with dates, times, bytes,and other forms of data to accomplish specific administrative tasks This chapter showsyou how VBScript handles these other data types and how you can use them in your ownscripts

Chapter 10: Controlling the Flow of Execution

The best administrative scripts can respond to changing conditions with internal logic,called control-of-flow This chapter shows you how your scripts can be made to evaluatevarious conditions and respond accordingly, perform repetitive tasks, and much more

Chapter 11: Built-in Scripting Objects

Much of VBScript’s power comes from its capability to join various operating systemobjects, and this chapter introduces you to your first set of those objects You’ll learn how

to manipulate network information, map drives, and much more—pretty much thing you need to write effective logon scripts

every-Chapter 12: Working with the File System

A common use of scripting is to manipulate files and folders, and this chapter introducesyou to the VBScript FileSystemObject, which provides a complete object model forworking with the file system You’ll learn to build a utility that scans Internet InformationServices (IIS) log files for error messages, a useful script for any environment!

VBScript, WMI, and ADSI Unleashed

Trang 24

Chapter 13: Putting It All Together: Creating Your First Script from Scratch

This is where you put everything from Part II together You’ll create a script that rotatesIIS log files, keeping the past 30 days worth of files in a special archive folder This

chapter guides you through the complete process of designing, writing, testing, and bleshooting the script In fact, it deliberately introduces some logic errors into the script

trou-so that you can see the debugging process in action

Part III: Windows Management Instrumentation and Active

Directory Services Interface

With the glue of VBScript under your belt, this part dives into the two most powerfultechnologies for administering Windows: Windows Management Instrumentation (WMI)and the Active Directory Services Interface (ADSI) These technologies provide administra-tive access to, and control over, nearly every aspect of the Windows operating system,from Windows NT to Windows Server 2003

Chapter 14: Working with ADSI Providers

Despite its name, ADSI isn’t just for Active Directory This chapter shows you how ADSIcan be used to interface with NT, Active Directory, Novell NDS, Exchange Server, andother types of directory services This chapter provides some basic examples of the types

of tasks you can perform with ADSI to get you started

Chapter 15: Manipulating Domains

With the ADSI basics out of the way, this chapter focuses on manipulating domain mation in a script You’ll learn how to query domain information, modify domain poli-cies such as password length, and much more

infor-Chapter 16: Manipulating Users and Groups

This chapter shows you how to write scripts that query and modify user and group mation This is one of the most common tasks you’ll perform with VBScript, and thischapter includes plenty of useful examples

infor-Chapter 17: Understanding WMI

WMI provides a hook into just about every portion of the Windows operating system,making it an incredibly useful tool for administrative scripts This chapter introduces you

to WMI and shows you a preview of what you can use it for in your environment

Chapter 18: Querying Basic WMI Information

Do you want to find out which users in your organization have a Pentium 4 computer?This chapter shows you how to write your own basic WMI queries, including those thatinvolve remote machines You’ll also learn basic WMI manipulation, which lets youmodify local and remote machine settings from within a script

Introduction

Trang 25

Chapter 19: Querying Complex WMI Information

Some WMI queries are more complex, such as querying the IP addresses from multiplenetwork adapters in multiple remote computers This chapter provides clear examples ofthese more complex WMI tasks, helping you learn to write enterprise managementscripts

Chapter 20: Putting It All Together: Your First WMI/ADSI Script

This is where it all comes together This chapter walks you through the process of ing, writing, testing, and debugging a complete WMI/ADSI script from scratch You’llfinish this chapter with a concrete example of the administrative capabilities of thesetechnologies, and then you’ll be ready to start writing your own scripts

design-Chapter 21: Testing and Debugging WMI and ADSI Queries

Getting the perfect WMI or ADSI query is critical to the success of your scripts, so thischapter focuses on tools you can use to develop those queries more interactively, test yourqueries, and have them fully refined before pasting them into your scripts

Part IV: Advanced Scripting Techniques

As you become a more experienced scripter, you’ll be ready to start saving time and bemore secure, with advanced techniques like script encryption, scripting components,script security, and so forth This part of the book gives you a comprehensive look at each of these technologies and shows you how to put them into use in your own

environment

Chapter 22: Modular Script Programming

If you find yourself cutting and pasting code—or worse, retyping it—this is the chapterfor you This chapter introduces you to modular scripting concepts, which make it easier

to reuse code between various scripts, saving you time and effort! By way of example, thischapter starts with a complex script that contains lots of useful code and then breaks itdown into easily reused modules

Chapter 23: Scripts Packaging and Protection

Are you worried that others will peek into your scripts and steal your ideas? Script ing and other techniques help protect your scripts from both Peeping Toms and potentialmisuse, so this chapter shows you how to set up, deploy, and use script packages withinyour environment

packag-Chapter 24: Scripting Security

Some folks think Microsoft made a huge mistake when it included VBScript in the

Windows operating system, but others disagree Properly configured, scripting can be assafe as any other type of application This chapter explains scripting security concepts andintroduces you to the tools that can make scripting a safe and valuable part of anycomputing environment

VBScript, WMI, and ADSI Unleashed

Trang 26

Chapter 25: Introduction to HTML Applications

HTML Applications, or HTAs, provide a way to mix VBScript and Hypertext MarkupLanguage (HTML) code to produce graphical scripts that look almost like full Windowsapplications They’re a great way to produce tools that you plan to share with less-experi-enced users or administrators This chapter gives you a quick start in building HTAs, alongwith an explanation of how they differ from more traditional VBScript projects

Chapter 26: Debugging Tips, Tools, and Techniques

By now, you’ll have seen your fair share of script bugs, and so this chapter shows youhow to prevent them from happening, find them quickly when they do happen, andsquash them just as quickly so that you can get on with your scripting

Part V: Ready-to-Run Examples

This part is a great way to wrap up the book—with a whole section on ready-made samplescripts that you can start using in your own environment In addition, these scripts—likeevery other script in this book—have complete, line-by-line explanations, making them aperfect reference guide as you start to create your own scripts from scratch

Chapter 27: Logon and Logoff Scripts

This chapter presents more complex logon and logoff scripts and gives you some ideas forhow scripting can make these important scripts more effective Of course, the line-by-lineexplanations make each script a useful reference for customizing your own scripts

Chapter 28: Windows and Domain Administration Scripts

Automating domain administration is probably one of the big reasons you started looking

at scripting in the first place, so this chapter presents a number of examples of tasks thatscripts can perform The detailed explanations with each script will help you rip themapart and customize them for your own use

Chapter 29: Network Administration Scripts

Network administration is ideally suited for scripting, and this chapter provides a handful

of examples that show you what’s possible The line-by-line explanations make it easy toput these into use in your own environment

Chapter 30: WMI and ADSI Scripts

These can be the toughest scripts to write because of the complexity and flexibility ofWMI and ADSI This chapter provides you with several ready-to-use scripts for commontasks, such as querying WMI, creating users and groups, and more These scripts can beeasily modified and incorporated into your own scripts, saving you scripting time!

Introduction

Trang 27

Appendix: Administrator’s Quick Script Reference

One of the toughest parts about VBScript is that it contains so much functionality It’susually pretty easy to figure out what you want a script to do; the tough part is oftenfiguring out how to make VBScript do it! This appendix provides an alphabetical list ofcommon tasks and gives the VBScript commands that perform each task You can use thisreference along with the VBScript documentation to make designing and writing scriptsmuch easier

Preparing to Use This Book

Before you dive in, you should make sure that your computers are ready for VBScript.Fortunately, any computer with Windows 2000 or later is ready to go out of the box, andthis book assumes that you’re doing your development work on either a Windows 2000–,Windows XP–, or Windows Server 2003–based computer

Typographical Elements

Books on programming can benefit a great deal from easy-to-understand typestyles andelements like the ones explained here These typestyles and elements are designed tomake the text easier to follow and to call your attention to special concerns

Monospaced type will be used to set off material that should be typed into the computer.For example, “select Runfrom the Start menu, type wbemtest, and click OK” sets off themenu selection, and what you need to type onscreen

Blocks of code and code lines that appear within the text appear in a monospaced font, as

in, “To change the contents of a variable, you can use Var1 = Trim(Var1).”

TIP

Tips provide shortcuts and other “insider advice” about scripting that you’ll find

valuable

NOTE

Notes provide cautions and other clarifications that will help you avoid problems or

further clarify complex concepts

VBScript, WMI, and ADSI Unleashed

Trang 28

You’ll also be directed to material that more thoroughly explains particular concepts,VBScript commands, and so forth Although you might not be a big fan of flipping backand forth through a book, these cross-references allow you to remain focused within eachchapter and guide you to more detailed explanations, when appropriate.

Finally, there are times when it is necessary to present an extended explanation of thing that isn’t critical to the task at hand In those cases, a sidebar is included A sidebar

some-is a cue that the information some-is useful, but it’s not really key to the main text; you’rewelcome to skip the sidebar and come back to it later

Sidebars

Sidebars make it easier to cover slightly off-topic information without distracting you

from the main text

Sample Scripts

Obviously, a book on scripting is going to have many code listings To make these asuseful as possible, each sample script is presented in a listing by itself with no comments

LISTING P.1 A Sample Script

‘Get the user’s name

sName = InputBox(“What is your name?”)

‘Display the user’s name

MsgBox “Your name is “ & sName

After each script, any changes you might need to make to get the script running in yourenvironment, such as changing computer or domain names, are presented You’ll findeach complete script included on the CD that accompanies this book Each chapter has aseparate folder and the script files are named with their listing number for easy reference

to detect the Cancel button, so it is assumed the user will type something and click OK

‘Get the user’s name

sName = InputBox(“What is your name?”)

Introduction

Trang 29

Finally, the script uses the MsgBoxstatement to redisplay the user’s name Notice the use

of the ampersand operator (&) to tack on the contents of the variable sName, which storeswhatever the user typed into the input box

‘Display the user’s name

MsgBox “Your name is “ & sName

Walk-throughs like this one will help you become more familiar with VBScript, what eachcommand does, and exactly how each sample script works

VBScript, WMI, and ADSI Unleashed

Trang 30

PART I

Introduction to

Windows Administrative Scripting

Trang 31

This page intentionally left blank

Trang 32

IN THIS CHAPTER

.Overview of Scripting

.Script Hosts

.ActiveX Scripting Languages

.The Component Object Model(COM)

.Critical Scripting SecurityIssues

.VBScript Versus WindowsPowerShell

CHAPTER 1

Scripting Concepts and

Terminology

In the past few years, scripting has become increasingly

popular with Windows administrators Visual Basic,

Scripting Edition—commonly known as VBScript—has

become especially popular because of its ease of use and

incredible flexibility Unfortunately, most books on

script-ing seemed to be focused toward developers, or at least

toward Windows administrators with a strong software

development background The result is that most

adminis-trators think that scripting is too complex for them, which

simply isn’t true In this book, I’ll introduce you to

script-ing from a purely administrative standpoint, startscript-ing with

this chapter, where I’ll explain exactly what I mean

by “scripting,” and how it all fits into Windows

administration

Overview of Scripting

Scripting means different things to different people Some

folks, for example, define a script as any series of computer

commands that are executed in a sequence, including

so-called scripts written in the MS-DOS batch language These

batch files were the mainstay of administrative automation

for many years, and many administrators still rely heavily

upon them today Other people define scripts as small

computer programs written in a high-level scripting

language, such as VBScript

Nobody’s really wrong, and scripting can mean all of these

things In fact, I’ve recently changed my opinion on the

subject, and agree that batch files are, in fact, scripts

They’re scripts in the most literal sense because when you

run a batch file, it’s exactly as if you were manually typing

every character in the script—the script just does so faster

Trang 33

VBScript is, in fact, an interpreted language, which is somewhat more complicated than a mere script It’s all splitting hairs, though! You can call all of them scripts and get away

with it

For the purposes of this book, scripting refers to the act of creating, executing, and

utiliz-ing small computer programs that are written in a high-end scriptutiliz-ing language, cally VBScript

specifi-Script Hosts

Scripts start out life as simple text files Try this: Open Windows Notepad on a Windows

XP computer, and type the following text:

Set objWMI = GetObject(“winmgmts:\\” & _

“.\root\cimv2”)

Set colOS = objWMI.ExecQuery(“SELECT “ & _

“* FROM Win32_OperatingSystem”)

For Each objOS In colOS

MsgBox “Serial number: “ & _

objOS.SerialNumber

Next

NOTE

In the production of this book, I tested each and every sample and script fragment on

my computer (running Windows XP), and they all worked at the time unless otherwisenoted in the text If a script isn’t working for you, first double-check your typing—

VBScript doesn’t tolerate typos! Next, ask for help I’ve set up a special forum on mysite, www.ScriptingAnswers.com, where you can ask questions about the scripts andsamples in this book I’ll do my best to help, but keep in mind, however, that some-

times things like your environment’s configuration, security policies, and other externalfactors might make a script impossible to run

Save the file as SampleScript.vbs Be sure to include the filename in double quotationmarks, or Notepad will append a txtfilename extension Now, locate the file in

Windows Explorer Make sure it has a vbsfilename extension and double-click it.Provided you’re running Windows XP and VBScript hasn’t been disabled on your

computer, you should see a small dialog box containing the serial number of your ing system Congratulations, you’ve just scripted!

operat-NOTE

For the time being, you don’t need to worry about how this script does what it does Inlater chapters, I’ll explain what each of these four lines of code accomplishes If youjust can’t wait, jump to Chapters 17 through 19, where I demonstrate how to use

Windows Management Instrumentation (WMI) to retrieve serial numbers and other

operating system information

CHAPTER 1 Scripting Concepts and Terminology

Trang 34

What actually happens when you double-click the VBS file? You can find out easily

enough From any Windows Explorer window, select Folder Options from the Tools menu.

Select the File Types tab and locate VBS in the list As shown in Figure 1.1, the vbsname extension is associated with the Microsoft Windows Script Host Whenever you

file-click a VBS file, Windows fires up the Script Host, tells it which script you clicked, and lets the Script Host run the script It’s similar to what happens when you

double-double-click a DOC file: Windows fires up Microsoft Word, tells it which file to open, andyour document appears

Script Hosts

FIGURE 1.1 File association for the VBS file type

The Windows Script Host (WSH) is a built-in component of Windows 2000, Windows XP,Windows Server 2003, Windows Vista, and later versions of Windows In fact, it’s underWindows File Protection for those operating systems, meaning you can’t delete or removethe WSH executable, Wscript.exe WSH is also included with Windows Me, is an optionalinstallation component in Windows 98, and can be added to Windows NT 4.0 and

Windows 95 through a free download from http://www.Microsoft.com/scripting

TIP

As of this writing, the latest version of WSH is 5.6, and you can download it for free

from http://www.Microsoft.com/scripting WSH is packaged in a Windows Installer file

(MSI), so you can easily deploy it to your client computers via Windows Group Policy

Trang 35

WSH is present in many Microsoft products, in various versions Here’s where you canfind WSH, along with the default versions:

Version tab

WSH is simply a Windows application that reads scripts and executes them Interestingly,

VBScript is not implemented right within WScript.exeitself WSH is actually intended to

be extensible, and it supports a number of scripting languages besides VBScript, such asJScript

WSH does have a number of built-in functions, which is why it’s nice to have the latestversion—newer versions and more built-in functions WSH can, for example, mapnetwork drives, connect to printers, work with environment variables, and modify theRegistry—all useful things to be able to do from within an administrative script

NOTE

Other applications—such as Microsoft Internet Explorer, Exchange Server, SQL Server,and IIS Active Server Pages—can serve as script hosts, too The nice part about learn-ing to create Windows administration scripts in VBScript is that you can quickly learn

to create Structured Query Language (SQL) scripts, Exchange scripts, or even Active

Server Pages, all using the same scripting language

ActiveX Scripting Languages

VBScript is just one of many ActiveX scripting languages These languages are written to a

specification developed by Microsoft, and scripts written in these languages can be

executed by WSH Each ActiveX scripting language is implemented by a scripting engine.

Usually, this dynamic link library (DLL) file interfaces with WScript.exeto interpretscripts, one line at a time, so that WSH can execute them Microsoft maintains two

CHAPTER 1 Scripting Concepts and Terminology

Trang 36

ActiveX scripting languages: VBScript and JScript JScript is the Microsoft implementation

of ECMAScript, which is the industry-standard version of Netscape’s JavaScript scriptinglanguage

NOTE

Ignoring company copyrights, trade names, and other legal matters, JScript,

ECMAScript, and JavaScript are more or less interchangeable terms

The scripting engines are maintained separately from WSH and carry their own versionnumbers However, both the latest version of VBScript and JScript are included with thebasic WSH installation, so you don’t need to worry about getting them individually

Other companies have produced ActiveX scripting languages, too For example,

VideoScript is an independent scripting language that works with WSH (http://www

videoscript.com) PerlScript and LiveScript are other popular ActiveX scripting languages.Scripting languages all have a few common characteristics

They are interpreted This means the scripting engine reads each line of script, one at

a time, and then executes it Execution requires the WSH to translate the scriptedinstructions into native Windows application programming interface (API) calls

Interpreted languages are slower than compiled languages like Visual Basic 6.0, where

the compiler translates the entire program into native Windows code all at once,

saving time later when the program is executed

They are text based In other words, you can create scripts with a simple text editor

like Notepad The downside is that anyone can read your script with Notepad, too.Most software applications’ code is compiled into a native binary format, making itvery difficult for end users to read the code Microsoft does offer an encoding utility(discussed in Chapter 27, “Logon and Logoff Scripts”) that allows you to protect

your source code from prying eyes

They are native In other words, your scripts only execute on Windows because WSH

itself only executes on Windows Contrast this with languages like Java, which can

be compiled and executed on any platform for which a Java Virtual Machine (JVM)

is available

They are easy to deploy Unlike compiled Visual Basic 6.0 applications, scripts don’t

usually require a bunch of DLLs and other files that you have to deploy, register,

and so forth Scripts can generally be copied from one computer to another and

executed as is

Perhaps the most powerful feature of VBScript is its capability to interface with the

Microsoft Component Object Model (COM)

ActiveX Scripting Languages

Trang 37

VBScript and NET: What Does the Future Hold?

I’m often asked how the release of VB NET and the NET Framework affect VBScript.After all, you don’t hear much mention of “VBScript.NET!”

It’s a complicated question The easy answer is this: Microsoft invested a lot of timeand money getting administrators to use VBScript, and administrators are using it

WSH will be included in new releases of Windows for some time to come, even if

Microsoft doesn’t do any further development In fact, Microsoft wrote a number of

command-line tools in VBScript, and includes them with Windows!

The Component Object Model (COM)

Software developers have always been encouraged to develop reusable code Imagine thatyou created some piece of code that retrieves the TCP/IP settings of a remote computer.Many administrators might want to use that code again So how do you make your codeavailable to them in an easy-to-use way?

Microsoft’s answer is COM, the Component Object Model COM is a specification that

describes how code can be packaged into objects, making them self-contained, easy

(rela-tively speaking) to deploy, and easy for other developers to use Physically, COM objectsare usually implemented in DLL files—which, if you check out the contents of a Windowscomputer’s System32folder, should tell you how pervasive COM is!

VBScript is completely capable of utilizing COM objects That’s a powerful feature becausemost of Windows’ functionality—and most other Microsoft applications’ functionality—isrolled up into COM components Working with email, Active Directory, Windows

Management Instrumentation (WMI), networking, the Registry, and more is all possiblethrough COM components, and, therefore, through VBScript I’ll cover objects in moredetail, including examples of how to use them in scripts, beginning in Chapter 5,

“Functions, Objects, Variables, and More,” and Chapter 11, “Built-In Scripting Objects,”shows you how to really take advantage of them

VBScript is even capable of creating COM components This means that you can useVBScript to create your Internet Protocol (IP)–retrieval software, package that software as aCOM component, and distribute it to other administrators This feature of scripting is

called Windows Script Components However, it’s a pretty advanced topic and, frankly, not

many administrators find it useful, so I won’t be covering it in any detail You can,however, obtain more information at http://www.ScriptingAnswers.com

Critical Scripting Security Issues

Sadly, Microsoft implemented VBScript without much thought for the consequences.Windows XP and Windows Vista, Microsoft’s most recent client operating systems, shipwith full scripting capability built-in and enabled by default The power of VBScript can

be used not only for beneficial administrative tasks, but also for malicious hacking, andmany viruses are based on VBScript or another ActiveX scripting language

CHAPTER 1 Scripting Concepts and Terminology

Trang 38

Administrators have reacted to the security threat of scripts in a number of ways:

DeletingWScript.exe Unfortunately, this doesn’t work on Windows 2000 or laterbecauseWScript.exeis protected with Windows File Protection If you delete it, itjust comes back

Disassociating the VB, VBS, JS, and other WSH file extensions, or reassociating them

to simply open in Notepad rather than in WSH This effectively disables scripting

Deploying antivirus software, such as Norton AntiVirus, which detects script tion and halts it

execu-Regrettably, disabling scripting usually disables it for good, meaning you can’t use ing for logon scripts, administrative tasks, and other beneficial purposes There’s a middleroad that you can take, however, which authorizes only certain scripts for execution Thismiddle road helps protect you against scripts written by hackers, but still allows scripts to

script-be used for administrative and logon purposes

Fortunately, Microsoft came to the table with security improvements that can make

scripting safe again, and Chapter 24, “Scripting Security,” is devoted to the topic of ing security

script-VBScript Versus Windows PowerShell

In late 2006, Microsoft launched an all-new tool for Windows administrative automation:Windows PowerShell Immediately, Windows administrators started asking, “Do I need tolearn this?” and “Will this replace VBScript?” The answers to those questions are a bit

complicated

First, let me make very clear that I love Windows PowerShell I think it’s a great tool with

some amazing capabilities, many of which parallel capabilities found in VBScript That

said, though, Windows PowerShell is just a tool It isn’t a religion or a spouse, which you

would normally only have one of—you can have as many tools as you want! While I

think you should absolutely learn Windows PowerShell—I even coauthored a book,

Windows PowerShell: TFM, on the topic—I also think you should learn VBScript.

VBScript was introduced around 1996, but it took nearly 5 or 6 years before Windows

administrators really started using it Now that Windows administrative automation is abigger deal, Windows PowerShell will enjoy a much faster adoption rate, but it’ll still be afew years Also, because Windows PowerShell is so new compared to VBScript, you won’tyet find the wealth of free community resources, examples, and so forth that VBScript hasbehind it Also, Windows PowerShell is a long-term strategic investment for Microsoft

Windows “Longhorn” Server, for example, won’t be built primarily on Windows

PowerShell, meaning VBScript will still be a big tool In fact, the “Server Core” version ofLonghorn relies heavily on a command-line tool written in VBScript by Microsoft! So,

VBScript has a long life ahead of it, and you should plan to use both VBScript and

Windows PowerShell as complementary parts of your administrative arsenal

VBScript Versus Windows PowerShell

Trang 39

Here’s another interesting fact: Microsoft isn’t developing VBScript any further Yes, that’s

right, folks, you’re about to learn how to use the only Microsoft product that’s finished, and

still in production! No new versions, no upgrades, no changes to worry about—it’s done!That’s literally the reason Microsoft isn’t developing it further: They feel it’s feature-complete and doesn’t require any additional work That should come as a huge relief toyou because it means what you’ll learn from this book will remain the same for years tocome Of course, one of my jobs at SAPIEN Technologies is to think of clever new ways togive VBScript more capability and functionality, so don’t regard VBScript as some old,deprecated, stagnant technology—it’s still very much alive and relevant!

Summary

VBScript is one of many available ActiveX scripting languages The scripts that you writeare executed by the Windows Script Host (WSH), which is physically implemented asWScript.exeand available for (or included with) all 32-bit Windows operating systems.VBScript—like other ActiveX scripting languages—is especially powerful because it caninterface with COM, the Microsoft Component Object Model COM allows VBScript to beinfinitely extended to perform other functions, including the majority of the Windowsoperating system functions In fact, COM integration sets VBScript apart from other so-called scripting technologies like old MS-DOS-style batch files

However, VBScript does bring up some important security issues that you’ll need to learn

to deal with in your environment Microsoft’s regrettable lack of planning when it comes

to scripting has resulted in a huge number of script-based viruses, making scripting a toolfor both good and evil Nonetheless, you can learn to configure your environment so thatonly approved (“good”) scripts run, allowing you to use the power and flexibility ofscript-based administration, while protecting your environment from malicious scripts

CHAPTER 1 Scripting Concepts and Terminology

Trang 40

IN THIS CHAPTER

.Windows Script Host

.Command-line Scripts

.Notepad and Script Editors

.Writing Your First Script

.Running Your First Script

.Debugging Your First Script

CHAPTER 2

Running Scripts

Suppose you have several scripts ready to run—what do

you do with them? Do you load them into Visual Basic and

compile them? How do you distribute them to your users

for use as logon scripts? What about when you’re ready to

start writing your own scripts? What tools are available,

and how well do they work? This chapter is designed to

introduce you to your scripting toolbox—the tools you’ll

need to write, run, edit, and debug your administrative

scripts

Windows Script Host

The most common way to run scripts is to use

WScript.exe, the graphical version of the Windows Script

Host (WSH), which I introduced in Chapter 1, “Scripting

Concepts and Terminology.” WScript is registered to handle

common scripting file extensions, so simply

double-clicking a vbor.vbsfile normally executes WScript.exe

and then asks it to execute the double-clicked script

To see WScript in action, follow these steps:

1 Right-click your desktop and select New; then point

to Text File

2 Rename the new text file to Sample1.vbs

3 Right-click the file and choose Edit By default,

Windows registers Notepad as the handler for the Edit

action, so a blank Notepad window opens

4 Type WScript.Echo “Displaying Output”and save

the file

5 Close Notepad

Ngày đăng: 01/06/2014, 11:59

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w