You will be producing useful scripts right away as you study the VBScript language and learn how to control nearly every aspect of the Windows operating system with WMI and the Active Di
Trang 1searching the Internet for examples-this book does it for you!"
-Greg A Marino, Senior Systems
Engineer/Consultant, Westtown Consulting Group, Inc.
Visual Basic Scripting (VBScript) and
Windows Management Instrumentation
Trang 2administrators grappling with the increasing complexity of Windows technologies.
However, busy admins have been without a straightforward guide to scripting until now.
Managing Windows(R) with VBScript and WMI
explains how Windows administrators can
effectively use VBScript to automate common administrative tasks and simplify complex
ones Detailed coverage of security concerns provides admins with the means for safely
using VBScript in Windows environments The book is organized around the problems you face daily, with reusable examples and
coverage of Windows NT, Windows 2000,
Windows XP, and Windows 2003.
This user-friendly reference demystifies
scripting and then shows you how to produce new scripts from scratch You will be
producing useful scripts right away as you
study the VBScript language and learn how to control nearly every aspect of the Windows operating system with WMI and the Active
Directory Services Interface (ASDI) You will
be able to build your own administrative Web
Trang 3technologies such as script encryption,
scripting components, and script security The book closes with still more ready-made
example scripts accompanied by complete
line-by-line explanations The CD includes all the code from the book and trial versions of PrimalScript 3.0 and VbsEdit A companion Web site provides updates and errata.
Inside you will find answers to such questions as:
How do you write effective logon scripts? Chapter 11
How do you write scripts that query and modify user and group information?
Chapter 16
How can you query the IP addresses from multiple network adapters in multiple
remote computers? Chapter 19
How can you design, write, run, test, and debug your own administrative Web
pages? Chapter 24
Trang 4How can you reuse code between various scripts? Chapter 25
Trang 5
• Table of Contents
• Examples
Managing Windows® with VBScript and WMI
Trang 13Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and Addison-Wesleywas aware of a trademark claim, the designations have beenprinted with initial capital letters or in all capitals
Windows is a registered trademark of Microsoft Corporation inthe United States and other countries
Screen shots reprinted by permission from Microsoft
Corporation
The author and publisher have taken care in the preparation ofthis book, but make no expressed or implied warranty of anykind and assume no responsibility for errors or omissions Noliability is assumed for incidental or consequential damages inconnection with or arising out of the use of the information orprograms contained herein
The publisher offers discounts on this book when ordered inquantity for bulk purchases and special sales For more
Trang 14systems (Computers) 3 VBScript (Computer program
language) I Title QA76.76.O63J6623 2004 005.4'4682dc222003026069
Copyright © 2004 by Pearson Education, Inc
All rights reserved No part of this publication may be
reproduced, stored in a retrieval system, or transmitted, in anyform, or by any means, electronic, mechanical, photocopying,recording, or otherwise, without the prior consent of the
publisher Printed in the United States of America Publishedsimultaneously in Canada
For information on obtaining permission for use of material fromthis work, please submit a written request to:
Pearson Education, Inc Rights and Contracts Department 75Arlington Street, Suite 300 Boston, MA 02116 Fax: (617) 848-7047
Trang 15Praise for Managing Windows ® with
VBScript and WMI
"This is the 'must-have' scripting guide for administrators
of all levels It shows what you need to get the job doneand how."
Joseph Niemi, Systems Engineer
"Finally, a step-by-step VBScripting book to make you looklike a programmer, without the time and sweat! Don't
waste your time searching the Internet for examples; thisbook does it for you!"
Greg A Marino, Senior Systems Engineer and Consultant Westtown Consulting Group, Inc
"Each chapter is like having a personal tutor at your sidethrough the iterative process of scripting, no matter whatyour experience level Whether you are writing complexscripts or simply automating repetitive tasks, I found thisbook truly hits the mark as the right tool to get the jobdone."
Joel Yoker, Program Manager
Microsoft Corporation
world understanding of how to use VBScript with WMI.The examples are clear and pertinent to the needs of theday-to-day system administrator."
"This book will provide any technical reader with a real-Bob Reselman, Principal
Cognitive Arts and Technologies
Trang 16Microsoft introduced Visual Basic, Scripting Editioncommonlyknown as VBScriptin the mid-'90s, positioning it as a native
replacement for Windows' aging command-line batch language,which was based on Microsoft's earliest operating system, MS-DOS VBScript was intended to be easy to learn, powerful, andflexible The language was included as an add-on to Windows
95 and Windows NT 4.0, was an optional installation componentincluded in Windows 98, and was included in all editions of
Windows Me, Windows 2000, Windows XP, and Windows Server2003
Software developers immediately seized upon VBScript for Webprogramming, particularly in Active Server Pages, Microsoft'srapid-development programming framework for the Web
However, Windows administratorsone of VBScript's initial targetaudienceswere left cold VBScript seemed to be much more
complicated than administrators' beloved MS-DOS-based batchlanguage, and many didn't see the need to learn an entirelynew batch language
When Windows 2000 and Active Directory came along, however,administrators found that Windows administration had become
a great deal more complex Suddenly, administrators were
searching for Resource Kit and other utilities that offered
automated administration, especially for repetitive tasks ActiveDirectory enabled the use of VBScript for logon and logoff
scripts, which seemed to promise more advanced use
environment manipulation At around the same time,
Microsoft's nạveté in releasing a powerful language like
VBScript with absolutely no security controls resulted in a hugewave of high-impact VBScript-based viruses, forcing
administrators to lock down their environments and removeVBScript as an option both for viruses and for administrative
Trang 17As a regular speaker at some of the country's top technical
conferences that focus on Windows technologies, including MCPTechMentor, the past few years I've given half- and full-day
sessions on VBScripting for Windows administrators, and thesessions have been incredibly popular In these sessions, I try
to provide just enough VBScript experience to make scriptingpossible, and then concentrate on accomplishing common
administrative tasks with VBScript I also cover the securityconcerns of VBScript and provide administrators with the meansfor safely using VBScript in their environments This book isessentially a written form of those sessions, greatly expandedwith more coverage of Windows Management Instrumentationand other advanced topics, and with more coverage of VBScriptsecurity 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 bookinvolves using VBScript to tell Windows to do things for you;you'll be able to ignore much of VBScript's complexity, using it
as a sort of electronic glue to combine various operating systemfunctions
Trang 18The only assumption I have about you is that you already knowhow to administer some version of Microsoft Windows You'llfind that most of the material in this book is suitable for
Windows NT, Windows 2000, and Windows Server 2003
environments, and it will continue to be useful through futureversions of Windows I do not assume that you have any
background in programming, and I'm not going to give you aprogramming background
You should have a desire to learn how to use what I call "thebatch language of the twenty-first century" and a wish to moveaway from clumsierand often more complexbatch files based onthe MS-DOS batch language Although some folks like to refer
to batch files as scripts, I don't; and when you see how easyand flexible VBScript is, you'll understand why!
Trang 19You can read this book in order from the Introduction to theAppendix However, if you already have some experience withVBScript, or if you just want to dive right into the more
complete example scripts, you can skip around as much as youlike I've organized this book in the same way that I organize
my live VBScripting sessions at conferences, so you may feelthat it's some time before you really get into the meat of
scripting I assure you, though, that each example in this
bookstarting in Chapter 1is focused on Windows administration.You'll get your feet wet right away!
I've also included In This Chapter elements at the start of eachchapter and Coming Up elements at the end of each chapter.These are brief paragraphs that are intended to help set thestage and help you decide if you need to read a particular
chapter or not They'll also help you decide which chapter toread next based on your individual needs and interests I hopethat these elementsalong with the cross-references I've
included in each chapterwill help you zip straight to the
scripting information that you need most
To help you decide where to start, here's a brief overview ofeach chapter
Scripting
Part I serves as an introduction to the world of scripting andprovides you with a methodology for approaching administrativetasks from a scripting standpoint One of the most difficult partsabout producing new scripts from scratch is the "Where do Istart?" factor, and I'll provide you with a framework for figuring
Trang 20Chapter 1 : Scripting Concepts and Terminology
As I've already implied, administrative scripting isn't hard-coreprogramming Instead, it's using VBScript as a sort of electronicglue to secure various bits of the Windows operating systemtogether In this chapter, I'll introduce you to those various bitsand set the stage with some basic terminology that you'll usethroughout this book
Chapter 2 : Running Scripts
Writing a script isn't much fun if you can't run the script, and sothis chapter will focus on the technologies used to execute
scripts You might be surprised to learn how many different
Microsoft products support scripting In this chapter, I'll showyou how far your scripting skills can really take you I'll alsointroduce you to some scripting tools that can make writing anddebugging scripts a bit easier
Chapter 3 : The Components of a Script
In this chapter, I'll present a complete administrative script, andthen break it down line-by-line to explain its various
components Although this chapter isn't necessary to learningadministrative scripting, it will help you write scripts that aremore reliable and easier to troubleshoot
Chapter 4 : Designing a Script
As I've mentioned already, one of the toughest aspects about
Trang 21planning for errors and creating a useful "resource kit" of scriptcomponents that you can reuse throughout your scripting
projects
Here's your official crash course to the VBScript language: justenough to make administration via script a possibility! The bestpart is that I won't use the trite "Hello, world" examples thatbooks for software developers often start out with Instead, I'llmake every example useful to you as a Windows administrator.That means you'll be producing simple, useful scripts at thesame time you're learning VBScript What could be better?
Chapter 5 : Functions, Objects, Variables, and
More
In this chapter, I'll show you the basic building blocks of anyscript and introduce you to some sample scripts that use eachbuilding block in a particular administrative task This is reallythe meat of administrative scripting, and you'll be able to writeuseful scripts when you're finished with this chapter
Chapter 6 : Input and Output
You can make your scripts more flexible by adding the ability todynamically change computer, user, and domain names, alongwith other information In this chapter, I'll show you how yourscript can collect information it needs to run and dynamically
Trang 22Chapter 7 : Manipulating Numbers
This chapter will explain how scripts can manipulate numbers,making it easier to create scripts that work with numeric data,such as user account data I'll also introduce you to VBScript'snumeric data handling and conversion commands, putting you
on the path to some great scripting techniques
Chapter 8 : Manipulating Strings
Stringsa fancy word for text dataare at the heart of most
scripting tasks In this chapter, I'll show you how VBScript dealswith strings and how you can easily integrate them into yourscripts
Chapter 9 : Manipulating Other Types of Data
Aside from text and numbers, your scripts may need to dealwith dates, times, bytes, and other forms of data to accomplishspecific administrative tasks In this chapter, I'll show you howVBScript handles these other data types and how you can usethem in your own scripts
Chapter 10 : Controlling the Flow of Execution
The best administrative scripts can respond to changing
conditions with internal logic, called control-of-flow In this
chapter, I'll show you how your scripts can be made to evaluatevarious conditions and respond accordingly, perform repetitivetasks, and much more
Trang 23Chapter 12 : Working with the File System
A common use of scripting is to manipulate files and folders,and in this chapter, I'll introduce you to the VBScript
FileSystemObject, which provides a complete object model forworking with the file system You'll learn to build a utility thatscans IIS log files for error messages, a useful script for anyenvironment!
debugging process in action
and Active Directory Services Interface
Trang 24Windows Management Instrumentation (WMI) and the ActiveDirectory Services Interface (ADSI) These technologies provideadministrative 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 In thischapter, I'll show you how ADSI can be used to interface with
NT, Active Directory, Novell NDS, Exchange Server, and othertypes of directory services I'll provide some basic examples ofthe types of tasks you can perform with ADSI to get you
started
Chapter 15 : Manipulating Domains
With the ADSI basics out of the way, I'll focus on manipulatingdomain information in a script You'll learn how to query domaininformation, modify domain policies like password length, andmuch more
Chapter 16 : Manipulating Users and Groups
In this chapter, you'll learn how to write scripts that query andmodify user and group information This is one of the most
common tasks you'll perform with VBScript, and I'll include
plenty of useful examples
Chapter 17 : Understanding WMI
Trang 25Windows operating system, making it an incredibly useful toolfor administrative scripts In this chapter, I'll introduce you toWMI and show you a preview of what you can use it for in yourenvironment
Chapter 18 : Querying Basic WMI Information
Do you want to find out which users in your organization have aPentium 4 computer? This chapter will show you how to writeyour own basic WMI queries, including those that involve
remote machines You'll also learn basic WMI manipulation,
which lets you modify local and remote machine settings fromwithin a script
Chapter 19 : Querying Complex WMI Information
Some WMI queries are more complex, such as querying the IPaddresses from multiple network adapters in multiple remotecomputers This chapter provides clear examples of these morecomplex WMI tasks, helping you learn to write enterprise
management scripts
Chapter 20 : Putting It All Together: Your First
WMI/ADSI Script
This is where it all comes together I'll walk you through theprocess of designing, writing, testing, and debugging a
complete WMI/ADSI script from scratch You'll finish this
chapter with a concrete example of the administrative
capabilities of these technologies, and then you'll be ready tostart writing your own scripts
Trang 26Part IV : Creating Administrative Web Pages
One popular use of Web technologies inside corporate networks
is to provide user self-service pages, such as a simple Web pagewhere users can reset their own passwords, if necessary In
Part IV, I'll give you a crash course on IIS and Active ServerPages (ASP) and show you how to start building your own
administrative Web pages
Chapter 21 : Active Server Pages Crash Course
ASP is a great way to create effective administrative Web
pages I'm not going to try to make you a Web developer or anHTML expert; the Web pages you'll create in this chapter won't
be pretty, but they'll be incredibly effective
Chapter 22 : Adding Administrative Script to a
Web Page
After you have a basic Web page ready, you can start addingscript to it to make the Web page perform administrative tasks.I'll provide examples of real-world tasks that you can start
using in your environment right away
Chapter 23 : Web Page Security Overview
Web pages have special security concerns, which I'll focus on inthis chapter I'll explain how IIS 5.0 and 6.0 process Web
pages, what you can and cannot easily accomplish from within aWeb page, and how you can create a secure, stable
environment for Web-based administrative scripts
Trang 27Chapter 24 : Putting It All Together: Your First
Administrative Web Page
You're now ready to design, write, run, test, and debug yourown administrative Web pages, and in this chapter, I'll step youthrough the entire progression When you're finished, you'll notonly have a ready-to-run administrative Web page to use, you'llalso be ready to start creating your own Web pages from
scratch Again, they might not be pretty, but they'll be
incredibly functional and useful
As you become a more experienced scripter, you'll be ready tostart saving time and be more secure, with advanced
techniques like script encryption, scripting components, scriptsecurity, and so forth In this part of the book, I'll give you acomprehensive look at each of these technologies and show youhow to put them into use in your own environment
Chapter 25 : Modular Script Programming
If you find yourself cutting and pasting codeor worse, retypingitthis is the chapter for you I'll introduce you to modular
scripting concepts, which make it easier to reuse code betweenvarious scripts, saving you time and effort! By way of example,we'll start with a complex script that contains lots of useful
code, and then break it down into easily reused modules
Chapter 26 : Using Script Components
Windows Script Components are the easy way to create your
Trang 28Chapter 27 : Encoded Scripts
Are you worried that others will peek into your scripts and stealyour ideas? Scripting encryption helps protect your scripts fromboth Peeping Toms and potential misuse, so I'll show you how
environment
I figured a great way to wrap up the book would be a wholesection on ready-made example scripts that you can start using
in your own environment Additionally, these scriptslike everyother script in this bookwill have complete, line-by-line
explanations, making them a perfect reference guide as youstart to create your own scripts from scratch
Trang 29Chapter 29 : Logon and Logoff Scripts
I'll use this chapter to present more complex logon and logoffscripts and to give you some ideas for how scripting can makethese important scripts more effective Of course, the line-by-line explanations will make each script a useful reference forcustomizing your own scripts
Chapter 30 : Windows and Domain Administration Scripts
Automating domain administration is probably one of the bigreasons you started looking at scripting in the first place, so I'lluse this chapter to present a number of examples of tasks thatscripts can perform The detailed explanations with each scriptwill help you rip them apart and customize them for your ownuse
Chapter 31 : Network Administration Scripts
Network administration is ideally suited for scripting, and in thischapter, I'll provide a handful of examples that will show youwhat's possible The line-by-line explanations will make it easy
to put these into use in your own environment
Chapter 32 : WMI and ADSI Scripts
These can be the toughest scripts to write due to the
complexity and flexibility of WMI and ADSI In this chapter, I'llprovide you with several ready-to-use scripts for common taskslike querying WMI, creating users and groups, and more Thesescripts can be easily modified and incorporated into your own
Trang 30commands that perform each task You can use this referencealong with the VBScript documentation to make designing andwriting scripts much easier
Trang 31Before you dive in, you should make sure that your computersare ready for VBScript Fortunately, any computer with Windows
2000 or later is ready to go out of the box, and I'll assume thatyou're doing your development work on either a Windows 2000,Windows XP, or Windows Server 2003based computer
Trang 32understand typestyles and elements like the ones I'll explainhere These typestyles and elements are designed to make thetext easier to follow and to call your attention to special
Books on programming can benefit a great deal from easy-to-concerns
Boldfaced type will be used to set off material that should betyped into the computer; boldfaced also will be used to signifyonscreen menu and/or dialog box selections For example,
"select Run from the Start menu, type wbemtest, and click
OK" sets off the menu selection, what you need to type
onscreen, and what should be clicked from the dialog box
Blocks of code and code lines that appear within the text willappear in a monospaced font, as in, "to change the contents of
Trang 33these cross-references will allow you to remain focused withineach chapter and will guide you to more detailed explanations,when appropriate
Finally, there are times when it is necessary to present an
extended explanation of something that isn't critical to the task
at hand In those cases, I'll use a sidebar A sidebar is a cuethat the information is useful, but it's not really key to the maintext; you're welcome to skip the sidebar and come back to itlater if you like
Trang 34environment, such as changing computer or domain names.
Trang 35accompanies this book I've created a separate folder for eachchapter and named the script files by their listing number foreasy reference
Sample ScriptsExplained
For each script in this book, I'll include a line-by-line
explanation of the script, so that you understand exactly what'sgoing on For example:
First, the sample script will display a dialog box where the user
can type his name By default, this dialog box includes an OK and Cancel button; I'm not providing any way to detect the
whatever 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 familiarwith VBScript, what each command does, and exactly how each
Trang 36example script works.
Trang 37Books never seem to write themselves, no matter how muchmoney I leave out for the elves at night Fortunately, behindevery author like myself stands an incredible team of
professionals, and the folks behind this book were truly at thetop of their industry So, special thanks to my literary agent atStudio B, Neil Salkind, and my acquisitions editor at Addison-Wesley, Sondra Scott: Thanks so much for your hard work intaking this book through the acquisitions process! I'd also like
to offer a special thanks to technical editors Bob Reselman andScott Worley for what was probably the most professional,
thorough review of any book I've written And a big thanks toall the other behind-the-scenes folks at Pearson Education whoworked so hard to bring this book to market
On a more personal level, I'd like to thank the folks in my lifewho make a project like this worthwhile: My parents, Rhondaand John; my ferrets, Clyde, Ziggy, Buffy, Pepper, and littleTigger; and my close and supportive friends, Sonya, Chris,Spencer, George, and Tom I'd also like to thank my businesspartner, Derek Melber, who has been so patient while I've beendevoting time to this book I'd also like to thank Keith, Dian,
and Kris at Microsoft® Certified Professional Magazine for all of
their personal and editorial support Finally, I'd like to thank allthe folks at Microsoft that I've enjoyed working with throughthe years: Amy, Dr Todd, Mary Beth, Ben, Harold, Kris,
Christine, Kim, Steve, Deb, Chuck, Peggy, Bucky, Barb, Alice,Joel, and Andy
Don Jones
BrainCore.Net, LLC
February 2004
Trang 38Don Jones is an independent consultant, speaker, and author,
and a founding partner of BrainCore.Net, the world leader inexam development and exam delivery technologies for the
Windows Server 2003 Delta Guide Don is now firmly based in
Las Vegas, Nevada, after spending more than two years
traveling the United States in a 40-foot RV
Trang 39Part I: Introduction to Windows Administrative Scripting
Chapter 1 Scripting Concepts and TerminologyChapter 2 Running Scripts
Chapter 3 The Components of a Script
Chapter 4 Designing a Script
Trang 40Terminology
IN THIS CHAPTER
Completely new to scripting? This is the chapter for you! You'll learn how scripts work, what they are, and how Windows uses them You'll also learn about key security issues, which will be covered in more detail in later chapters.
In the past few years, scripting has become increasingly
popular with Windows administrators Visual Basic, ScriptingEditioncommonly known as VBScripthas become especiallypopular, due to its ease of use and incredible flexibility
Unfortunately, most books on scripting seemed to be focusedtoward developers, or at least toward Windows administratorswith a strong software development background The result isthat most administrators think that scripting is too complex forthem, which simply isn't true In this book, I'll introduce you toscripting from a purely administrative standpoint, starting withthis chapter, where I'll explain exactly what I mean by
"scripting," and how it all fits into Windows administration