Compact Disc 1. Send us your feedback «Previous Next» Microsoft Windows 2000 Scripting Guide

Similar documents
Windows Script Host Fundamentals

Managing and Maintaining a Microsoft Windows Server 2003 Environment, Second Edition

Overview. Program Start VB SCRIPT SIGNER. IT Services

6.001 Notes: Section 15.1

Creating Word Outlines from Compendium on a Mac

This chapter is intended to take you through the basic steps of using the Visual Basic

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

DOWNLOAD PDF ABSOLUTE BEGINNERS GUIDE TO MICROSOFT OFFICE ONENOTE 2003 (ABSOLUTE BEGINNERS GUIDE)

WINDOWS POWERSHELL 3.0 FIRST STEPS BY ED WILSON DOWNLOAD EBOOK : WINDOWS POWERSHELL 3.0 FIRST STEPS BY ED WILSON PDF

TERMINOLOGY MANAGEMENT DURING TRANSLATION PROJECTS: PROFESSIONAL TESTIMONY

XP: Backup Your Important Files for Safety

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

[Compatibility Mode] Confusion in Office 2007

Installation Guide. Tivoli Decision Support 2.0

PYTHON PROGRAMMING FOR BEGINNERS: AN INTRODUCTION TO THE PYTHON COMPUTER LANGUAGE AND COMPUTER PROGRAMMING BY JASON CANNON

As enterprise networks. Exploring the Windows Management Instrumentation Feature of Windows The Windows Management BY SUSAN EISENHARD

Exsys RuleBook Selector Tutorial. Copyright 2004 EXSYS Inc. All right reserved. Printed in the United States of America.

DOWNLOAD PDF LEARN TO USE MICROSOFT ACCESS

GUARD1 PLUS Manual Version 2.8

SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7

PROGRAMMING: PRINCIPLES AND PRACTICE USING C++ (2ND EDITION) BY BJARNE STROUSTRUP

SyncFirst Standard. Quick Start Guide User Guide Step-By-Step Guide

Bits and Bytes. Here is a sort of glossary of computer buzzwords you will encounter in computer use:

Introduction to Programming

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

COPYRIGHTED MATERIAL. An Introduction to Computers That Will Actually Help You in Life. Chapter 1. Memory: Not Exactly 0s and 1s. Memory Organization

6.001 Notes: Section 1.1

Cognitive Disability and Technology: Universal Design Considerations

Clean & Speed Up Windows with AWO

Secrets of Profitable Freelance Writing

Some (semi-)advanced tips for LibreOffice

Hello! ios Development

An Overview of Visual Basic.NET: A History and a Demonstration

DOWNLOAD PDF SQL SERVER 2012 STEP BY STEP

Intro. Scheme Basics. scm> 5 5. scm>

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

Chapter 11: Editorial Workflow

Running Wordstar 6 on Windows 7 Using vdos

These are notes for the third lecture; if statements and loops.

Creating a new form with check boxes, drop-down list boxes, and text box fill-ins. Customizing each of the three form fields.

Memory Addressing, Binary, and Hexadecimal Review

It is written in plain language: no jargon, nor formality. Information gets across faster when it s written in words that our users actually use.

Lecture Notes on Memory Layout

ITConnect KEEPING TRACK OF YOUR EXPENSES WITH YNAB

To get started with Visual Basic 2005, I recommend that you jump right in

WordPress Tutorial for Beginners with Step by Step PDF by Stratosphere Digital

Burning CDs in Windows XP

Setting up a ColdFusion Workstation

Lab: Supplying Inputs to Programs

Week - 01 Lecture - 04 Downloading and installing Python

Incident Response Tools

RICH ENTERPRISES. Small Business Series. Getting Started with HTML

Automating Administration with Windows PowerShell 2.0

AppleScripting the Finder Preview

Preprocessor Directives

ABCs of Direct Mail. Tips for More Effective Marketing Publications

Variables and Data Representation

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

MITOCW watch?v=kz7jjltq9r4

QuickBooks 2006 Network Installation Guide

with TestComplete 12 Desktop, Web, and Mobile Testing Tutorials

SAMPLE CHAPTER SECOND EDITION. Don Jones Jeffery Hicks Richard Siddaway MANNING

An administrator s guide

What is version control? (discuss) Who has used version control? Favorite VCS? Uses of version control (read)

Virtual CD TS 1 Introduction... 3

The Dynamic Typing Interlude

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

(Refer Slide Time: 06:01)

High Performance Computing Prof. Matthew Jacob Department of Computer Science and Automation Indian Institute of Science, Bangalore

Excel programmers develop two basic types of spreadsheets: spreadsheets

2016 All Rights Reserved

12 Key Steps to Successful Marketing

EssEntial indesign skills Brought to you By InDesign

The notion of functions

Introduction 1. Getting Started 9. Working with Virtual CD OPS 21

1: Introduction to Object (1)

Game keystrokes or Calculates how fast and moves a cartoon Joystick movements how far to move a cartoon figure on screen figure on screen

Quicken 2015 The Official Guide For Windows! Ebooks Free

EMCO MSI Package Builder Professional 7. Copyright EMCO. All rights reserved.

1 Installation (briefly)

MicroSurvey Users: How to Report a Bug

Financial Statements Using Crystal Reports

Preface. The ClickBank Success Forum. Chapter 1. Introduction. Chapter 2: Using the forum. Chapter 3: Advertising at the forum

Chapter 1 Introduction

How to Get a Website Up and Running

Hello, and welcome to another episode of. Getting the Most Out of IBM U2. This is Kenny Brunel, and

MEAP Edition Manning Early Access Program Learn Windows Server in a Month of Lunches Version 5

Free Downloads Microsoft Access 2010 Step By Step

Deploying and Using SLIM Suite in a Global Environment

In further discussion, the books make other kinds of distinction between high level languages:

Figure 1-1. When we finish Part 2, our server will be ready to have workstations join the domain and start sharing files. Now here we go!

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

(Refer Slide Time: 1:43)

Learn how to use bold, italic, and underline to emphasize important text.

If Statements, For Loops, Functions

A Beginner s Guide to Successful Marketing

Fundamental C# Programming

Section 2. Sending s

Deploying Windows Server 2008 with System Center

Lesson 1: Preparing for Installation

Transcription:

Compact Disc 1 Introduction Welcome to the. As computers and computer networks continue to grow larger and more complex, system administrators continue to face new challenges. Not all that long ago, system administration was limited to managing a handful of computers (most located within the same general area), a relatively small number of user accounts, and a few applications, many of which had no knowledge of, or need for, a local area network. Today, of course, system administrators often manage hundreds, and even thousands of computers, as well as a corresponding number of user accounts. These computers, many situated in remote locations, run scores of applications, and rely heavily on networks and networked resources including file servers, Dynamic Host Configuration Protocol (DHCP) and Domain Name System (DNS) servers, and shared printers. This has made it imperative for system administrators to find management solutions that: Can be tailored to meet the unique needs of the organization. Can operate against multiple computers, and against remote computers. Are quick, easy, and cost-effective. Scripts provide all of these capabilities, and more. In addition, scripting requires no investment in hardware or software beyond a computer running Microsoft Windows 2000. This book introduces you to the scripting technologies included in the Windows 2000 platform. It teaches you the basic concepts underlying such key scripting technologies as VBScript, Windows Script Host (WSH), Active Directory Service Interfaces (ADSI), and Windows Management Instrumentation (WMI). In addition, the book includes hundreds of pre-written scripts that carry out such routine, yet important, system administration tasks as: backing up and clearing event logs; monitoring process use; reading and writing to the registry; and managing user accounts, computer accounts, printers, and services. You can use these scripts as provided, or you can apply the principles of the Microsoft scripting technologies to modify them to meet your exact needs. Send us your feedback Compact Disc The following contents are included on the Windows 2000 Scripting Guide companion CD: Windows 2000 Scripting Guide (SagSAS.chm). A searchable Help file containing the online version of the Windows 2000 Scripting Guide. CD-ROM Release Notes (Readme.txt). The release notes for the contents of Windows 2000 Scripting Guide companion CD. Script repository (Scripts.chm). A searchable Help file containing scripts for use with WMI, ADSI, VBScript, and other Microsoft Scripting technologies. Compact Disc 1

2 Document Conventions Scriptomatic tool (Scriptomatic.hta). A hypertext application you can use write WMI scripts. Scriptomatic documentation (Write WMI Scripts Like the Pros.doc). Documentation for the Scriptomatic tool. Windows Script 5.6 (Scripten.exe). The installer for Microsoft Visual Basic Scripting Edition (VBScript) Version 5.6, JScript Version 5.6, Windows Script Components, Windows Script Host 5.6, and Windows Script Runtime Version 5.6. These are the most recent versions of each technology at this writing and are covered in this book. Please note that this installer runs only on Windows 2000 operating systems. Windows Script 5.6 Documentation (Scrdoc56en.exe). A searchable reference and conceptual Help file for Windows Script 5.6. Microsoft Word viewer. If you do not have Microsoft Word installed on your computer, install this viewer to see the Scriptomatic documentation. Links to Microsoft Press. Links to the Microsoft Press Support site, which you can search for Knowledge Base articles, and to the Microsoft Press product registration site, which you can use to register this book online. Send us your feedback Document Conventions The following art symbols and text conventions are used throughout this book. Scripting Diagram Symbols Use the following table of symbols as a resource for understanding the scripting graphics included in this book. Symbol Meaning Object Method Property Event Collection object Reader Alert Conventions Item property of a collection object Reader alerts are used throughout this book to notify you of both supplementary and essential information. The following table explains the meaning of each alert. Reader Alert Meaning 2 Document Conventions

Scripting Concepts and Technologies for System Administration 3 Tip Note Alerts you to supplementary information that is not essential to the completion of the task at hand. Alerts you to supplementary information. Important Alerts you to supplementary information that is essential to the completion of a task. Caution Warning Alerts you to possible data loss, breaches of security, or other more serious problems. Alerts you that failure to take or avoid a specific action might result in physical harm to you or to the hardware. Command-line Style Conventions The following style conventions are used in documenting scripting and command-line tasks throughout this book. Element bold font Italic font Monospace font Code samples. Command Syntax Output Meaning Characters that you type exactly as shown, including commands and parameters. User interface elements are also bold. Variables for which you supply a specific value. For example, Filename.ext can refer to any valid file name. Command that is typed at the command prompt. Syntax of script elements. Output from running a script. Send us your feedback Support Policy Microsoft does not support the software supplied in the Windows 2000 Scripting Guide. Microsoft does not guarantee the performance of the scripting examples, job aids, or tools, bug fixes for the tools, or response times for answering questions. However, we do provide a way for customers who purchase the Windows 2000 Scripting Guide to report any problems with the software and receive feedback for such issues. You can do this by sending e-mail to rkinput@microsoft.com. This e-mail address is only for issues related to the Windows 2000 Scripting Guide. For issues related to the Windows 2000 operating systems, please refer to the support information included with your product. Send us your feedback Scripting Concepts and Technologies for System Administration Scripting Concepts and Technologies for System Administration 3

4 Introduction to Windows Script Technologies To write scripts for managing Windows-based computers, you need a solid understanding of the scripting technologies included in the Windows 2000 operating system. Part 1 of this book introduces key concepts for each of Microsofts primary system administration scripting technologies, including: Microsoft Visual Basic Scripting Edition (VBScript); Windows Script Host (WSH); the Script Runtime library; Active Directory Service Interfaces (ADSI); and Windows Management Instrumentation (WMI). In This Part Introduction to Windows Script Technologies VBScript Primer WSH Primer Script Runtime Primer ADSI Scripting Primer WMI Scripting Primer Send us your feedback Introduction to Windows Script Technologies This is a book about scripting for system administrators. If you are like many system administrators, you might be wondering why this book is targeted towards you. After all, scripting is not the sort of thing system administrators do. Everyone knows about scripting: scripting is hard; scripting is time-consuming; scripting requires you to learn all sorts of technical jargon and master a whole host of acronyms WSH, WMI, ADSI, CDO, ADO, COM. System administrators have neither the time nor the requisite background to become script writers. Or do they? One of the primary purposes of this book is to clear up misconceptions such as these. Is scripting hard? It can be. On the other hand, take a look at this script, which actually performs a useful system administration task: Set objnetwork = CreateObject("WScript.Network") objnetwork.mapnetworkdrive "X:", "\\atl-fs-01\public" Even if you do not know the first thing about scripting and even if you are completely bewildered by line 1 of the script, you can still make an educated guess that this script must map drive X to the shared folder \\atl-fs-01\public. And that is exactly what it does. If you already understand system administration that is, if you know what it means to map a drive and you understand the concept of shared folders and Universal Naming Convention (UNC) paths the leap from mapping drives by using the graphical user interface (GUI) or a command-line tool to mapping drives by using a script is not very big. Note If you are already lost because you are not sure what is meant by scripting in the first place think of scripting in these terms: 4 Introduction to Windows Script Technologies

Introduction to Windows Script Technologies 5 Do you ever find yourself typing the same set of commands over and over to get a certain task done? Do you ever find yourself clicking the same set of buttons in the same sequence in the same wizard just to complete some chore and then have to repeat the same process for, say, multiple computers or multiple user accounts? Scripts help eliminate some of this repetitive work. A script is a file you create that describes the steps required to complete a task. After you create the script, you can "run" that script, and it will perform all of the steps for you, saving you a great deal of time and energy. You need only create the script once, and then you can reuse it any time you need to perform that task. Admittedly, not all scripts are as simple and intuitive as the one just shown. But if you thumb through this book, you will find that the vast majority of scripts almost all of which carry out useful system administration tasks are no more than 15 or 20 lines long. And with a great many of those, you can read the code and figure out what is going on regardless of your level of scripting experience. Does scripting take too much time? It can: If you write a script that is 500 lines long (and you probably never will), the typing alone will take some time. But it is important to balance the time it takes to write a script with the time that can be saved by using that script. For example, here is a script that backs up and clears all the event logs on a computer: strcomputer = "." Set objwmiservice = GetObject("winmgmts:" _ & "{impersonationlevel=impersonate, (Backup, Security)}!\\" _ & strcomputer & "\root\cimv2") Set collogfiles = objwmiservice.execquery _ ("Select * from Win32_NTEventLogFile") For Each objlogfile in collogfiles strbackuplog = objlogfile.backupeventlog _ ("c:\scripts\" & objlogfile.logfilename & ".evt") objlogfile.cleareventlog() Next Admittedly, this script is not as intuitive as the drive-mapping script. Furthermore, to write a script like this, you will need to learn a little bit about scripting in general, and about Windows Management Instrumentation (WMI) in particular. And then you still have to type it into Microsoft Notepad, all 11 lines worth. This one might take you a little bit of time. But think of it this way: How much time does it take you to manually back up and clear each event log on a computer. (And that assumes that you actually do this; the manual process can be so tedious and time-consuming that many system administrators simply forgo backing up and clearing event logs, even though they know this task should be done on a regular basis.) With a script, you can back up and clear event logs in a minute or two, depending on the size of those logs. And what if you take an extra half hour or so and add code that causes the script to back up and clear all the event logs on all your computers? You might have to invest a little time and energy in learning to script, but it will not be long before these scripts begin to pay for themselves. Point conceded. But even though scripting does not have to be hard and does not have to be time-consuming, it still requires you to learn all the technical mumbo-jumbo, right? Sure, if you want to be an expert in scripting. But consider this script, which returns the names of all the services installed on a computer: strcomputer = "." Set objwmiservice = GetObject("winmgmts:" & _ "{impersonationlevel=impersonate}!\\" & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery("select * from Win32_Service") For Each objitem in colitems Wscript.Echo objitem.name Next Under the covers, this is a fairly complicated script. Among other things, it: Introduction to Windows Script Technologies 5

6 Introduction to Windows Script Technologies Makes use of Automation object methods and properties. Utilizes Microsoft Visual Basic Scripting Edition (VBScript) constructs such as the For Each loop to iterate through the elements within a collection. Requires a COM (Common Object Model) moniker. Uses WMI object paths, namespaces, and classes. Executes a query string written in the WMI Query Language. That is an awful lot to know and remember just to write a seven-line script. No wonder people think scripting is hard. But the truth is, you do not have to fully understand COM and Automation to write a script like this. It does help to know about these things: As in any field, the more you know, the better off you are. But suppose what you really want is a script that returns the names of all the processes currently running on a computer instead of one that returns the names of all the installed services. Here is a script that does just that: strcomputer = "." Set objwmiservice = GetObject("winmgmts:" & _ "{impersonationlevel=impersonate}!\\" & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery("select * from Win32_Process") For Each objitem in colitems Wscript.Echo objitem.name Next What is so special about this script? Nothing. And that is the point. Look closely at the single item in boldface (Win32_Process). This is the only part of the process script that differs from the service script. Do you know anything more about COM monikers or WMI object paths than you did a minute ago? Probably not, and yet you can still take a basic script template and modify it to return useful information. Want to know the name of the video card installed on a computer? Try this script: strcomputer = "." Set objwmiservice = GetObject("winmgmts:" & _ "{impersonationlevel=impersonate}!\\" & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery("select * from Win32_VideoController") For Each objitem in colitems Wscript.Echo objitem.name Next Is it always this easy? No, not always. And these examples sidestep a few issues (such as, "How do I know to type in Win32_VideoController rather than, say, Win32_VideoCard?" or, "What if I want to know more than just the name of the video card?"). The point is not that you can start writing scripts without knowing anything; the point is that you can start writing scripts without knowing everything. If you want to master COM monikers and WMI object paths before you write your first script, thats fine. And if you prefer to just start writing scripts, perhaps by building on the examples in this book, thats fine too. You can always start writing and using scripts today, and then go back and learn about COM monikers and WMI object paths tomorrow. How Did Scripting Acquire Such a Bad Reputation? If scripting is so easy, then, how did it gain a reputation for being so hard? And if it is so valuable, why arent more system administrators using it? After all, few system administrators knowingly turn their backs on something that will make their lives easier. There are probably many reasons for this, but at least part of the problem dates back to the birth of the Microsoft Windows Script Technologies. Both VBScript and Microsoft JScript (the two scripting languages included with the Microsoft Windows operating system) began as a way to add client-side scripting to Web pages. This was great for Internet developers, but of little use to the typical system administrator. As a result, scripting came to be associated with Web page development. (Even today, many of the code samples in the official Microsoft documentation for VBScript show the code embedded in a Web 6 Introduction to Windows Script Technologies

Introduction to Windows Script Technologies 7 page.) Later on, Windows Script Host (WSH) was born. WSH provided a way for scripting languages and scripting technologies to be used outside Internet Explorer; in fact, WSH was aimed squarely at system administration. Nevertheless, scripting still failed to take the system administration world by storm. Initially, this was probably due to a lack of documentation and a lack of proper positioning. It was difficult to find information about using VBScript or JScript as a tool for system administration; it was next-to-impossible to find information about technologies such as WMI or Active Directory Service Interfaces (ADSI). Even when these technologies were documented (typically in software development kits), the documentation was aimed at programmers; in fact, code samples were usually written in C++ rather than a scripting language. For example, suppose you are a typical system administrator (with substantial knowledge of Windows and minimal knowledge of programming). And suppose you looked up scripting on Microsofts Web site and saw sample code that looked like this: int main(int argc, char **argv) { HRESULT hres; hres = CoInitializeEx(0, COINIT_MULTITHREADED); // Initialize COM. if (FAILED(hres)) { cout << "Failed to initialize COM library. Error code = 0x" return 1; // Program has failed. } << hex << hres << endl hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IDENTIFY, NULL, EOAC_NONE, 0 ); Needless to say, very few system administrators saw WMI or ADSI as a tool that would be useful for them. Today, of course, there is no dearth of scripting-related literature; a recent search of a major online bookstore with the keyword "VBScript" returned 339 titles. That is the good news. The bad news is that most of those titles take one of two approaches: Either they continue to treat scripting as a tool for Web developers, or they focus almost exclusively on VBScript and WSH. There is no doubt that VBScript and WSH are important scripting technologies, but by themselves the two do not enable you to carry out many useful system administration tasks. Of the 339 scripting books found in the search, only a handful look at scripting as a tool for system administration, and only a few of those cover the key technologies WMI and ADSI in any depth. A system administrator who grabs a scripting book or two at random might still fail to understand that scripting can be extremely useful in managing Windows-based computers. How This Book Helps So is the simply scripting book number 340, or does it somehow differ from its predecessors? In many ways, this book represents a new approach to scripting and system administration. In fact, at least four characteristics help distinguish this book from many of the other books on the market: The focus is on scripting from the point of view of system administration. This book includes many of the same chapters found in other scripting books; for example, it has a chapter devoted to VBScript. The difference is that the chapter is focused on the VBScript elements that are most useful to system administrators. System administrators need to work extensively with COM, so the VBScript chapter features detailed explanations of how to bind to and make use of COM objects within a script. System administrators have little use for calculating arctangents and cosines. Hence, these subjects are not covered at all, even though it is possible to make these calculations using VBScript. Introduction to Windows Script Technologies 7

8 Introduction to Windows Script Technologies This book is task-centered rather than script-centered. In some respects, the scripts included in this book are an afterthought. Sometimes a book author will create a bunch of interesting scripts and then compose the text around those items. This book takes a very different approach: Instead of starting with scripts, the authors identified key tasks that system administrators must do on a routine basis. Only after those tasks were identified and categorized did they see whether the tasks could even be scripted. In that sense, this is not so much a book about scripting as it is a book about efficiently managing Windows-based computers. As it happens, the suggested ways to carry out these tasks all involve scripts. But the scripts could easily be removed from the book and replaced with command-line tool or GUI equivalents, and the book would still have value. This book combines tutorial elements with practical elements. Some books try to teach you scripting; thus they focus on conceptual notions and, at best, pay lip service to practical concerns. Others take the opposite approach. In those cases, the focus is on the practical: The books present a host of useful scripts, but make little effort to help you understand how the scripts work and how you might modify them. This book tries to combine the best of both worlds; for example, any time a useful system administration script is presented, the script is accompanied by a step-by-step explanation of how the script works and how it might be adapted to fit your individual needs. This book recognizes that, the larger the organization, the more pressing the need to automate procedures. If you are the system administrator for an organization that has a single computer, you might still find the scripts in this book useful. To be honest, though, you would probably find it faster and easier to manage your lone computer by using the GUI. If you have 100 computers, however, or 1,000 computers, the value of scripts and scripting suddenly skyrockets. In recognition of this fact, the book includes an entire chapter "Creating Enterprise Scripts" that discusses how the sample scripts in this book can be modified for use in organizations with many computers. How Do You Know if This Book is for You? Officially, this book was written for "system administrators in medium to large organizations who want to use scripting as a means to manage their Windows-based computers." That group (amorphous as it might be) will likely make up the bulk of the readership simply because 1) the book revolves around scripting system-administration tasks, and 2) system administrators in medium to large organizations are the people most likely to need to use scripts. However, the book should be useful to anyone interested in learning how to script. The techniques discussed throughout the book, while focused on medium to large organizations, are likely to prove useful in small organizations as well. These techniques are typically used to carry out system administration tasks, but many of them can be adapted by application programmers or Web developers. The book does not discuss scripting as a method of managing Microsoft Exchange Server; however, Microsoft Exchange Server can be managed using WMI. Because of this, Exchange administrators might be interested not only in the chapter "WMI Scripting Primer" but also in the chapter "VBScript Primer," which discusses generic techniques for working with Automation objects. This book also tries to provide information that will be useful to people with varying levels of scripting knowledge and experience. No scripting background is assumed, and if you read the book from cover to cover, you will start with the fundamental principles of scripting and gradually work your way through more complicated scenarios. But what if you already know VBScript but do not know much about ADSI? Skip directly to "ADSI Scripting Primer." What if you understand the basic principles of WMI but need to know how to create and terminate processes using WMI? Go right to the "Processes" chapter. There is something for everyone in this book: No knowledge or experience is required, but that does not mean that the book does not occasionally discuss a task or technique that might be a bit more advanced. And what if you have already mastered every scripting technique ever created? In that case, the book will likely be useful as a reference tool; after all, even those who know everything about WMI have rarely taken the time to memorize all the class names, methods, and properties. For those people, the tables in the task-based chapters might well make up for the fact that some of the explanations are aimed at beginners instead of experts. 8 Introduction to Windows Script Technologies

Introduction to Windows Script Technologies 9 What Is in This Book The Windows 2000 Scripting Guide is divided into three parts: Conceptual chapters. The conceptual chapters offer comprehensive primers on the primary scripting technologies from Microsoft, including Windows Script Host (WSH), VBScript, WMI, ADSI, and the Script Runtime library. These are tutorial-type chapters, all written from the standpoint of a system administrator, and all written under the assumption that the reader has little, if any, scripting experience. Task-based chapters. For the task-based chapters, core areas of system administration were identified, including such things as managing services, managing printers, and managing event logs. Within each of these core areas, 25 or so common tasks were also identified, such as starting and stopping services, changing service account passwords, and identifying the services running on a computer. Each task includes 1) a brief explanation of the task and why it is important, 2) a sample script that performs the task, and 3) a step-by-step explanation of how the script works and how you might modify it to fit your own needs. Enterprise chapters. The enterprise chapters cover a range of topics, including guidelines for setting up a scripting infrastructure and best practices to consider when writing scripts as part of an administrative team. These chapters also describe different ways to enterprise-enable a script, for example, writing a script that performs an action on all your domain controllers or on all your user accounts, or a script that accepts arguments from a text file or a database. You do not have to begin on page 1 and read the entire book from start to finish. The book is designed so that you can skip around and read only the content that interests you. Are you less interested in a conceptual understanding of WMI than you are in learning how to manage services by using scripts? Then start off by reading the "Services" chapter; there is no reason to read all of the preceding chapters. If you are new to scripting, you might find it useful to read about VBScript and WMI first, but this is not a requirement. Consider this book to be a smorgasbord of scripting techniques: You are free to pick and choose as you please. In fact, if you are as interested in using scripts as you are in writing them, you might want to start with the task-based chapters. Read a chapter, copy and run the scripts, and see what happens. If you then want to better understand how the scripts work or would like to modify them so that they better fit your individual needs, go back and read up on the conceptual information. About the Scripts Used in This Book Most of the people who saw draft copies of this book expressed surprise and gratitude that the scripts were so short; many were used to scripting books in which a sample script might cover two or three pages, and had no idea that scripting could be so simple. However, some people were shocked by the fact that the scripts were so bare-boned. For example, very few of the scripts in the book include error handling; why would you write a production-level system administration script without including things such as error handling? The answer is simple: The scripts in this book were never intended to be production-level system administration scripts. Instead, they are included for educational purposes, to teach various scripting techniques and technologies. Most of them can be used as-is to carry out useful system administration tasks, but that is just a happy coincidence; this book and the script samples are designed to teach you how to write scripts to help you manage your computing infrastructure. They were never intended to be a management solution in and of themselves. Finding All the Pieces Introduction to Windows Script Technologies 9

10 Introduction to Windows Script Technologies Keeping the scripts simple does not mean that concepts such as error handling are ignored; script writers definitely have a need for error handling, they have a need for parsing command-line arguments, and they have a need for creating scripts that run against more than one computer (for example, against all their Dynamic Host Configuration Protocol [DHCP] servers or against all the computers with accounts in a particular Active Directory container). Because of that, these techniques are covered in considerable detail in "Creating Enterprise Scripts" and "Scripting Guidelines" in this book. In other words, although this book does not include any 500-line scripts that make use of every possible scripting technique, all of these scripting techniques are demonstrated somewhere in the book. If you wanted to, you could easily take a number of the small sample scripts and stitch them together to create a 500-line production-level super script. By leaving out such things as error handling, the scripts were kept as short as possible, and the focus remained on the task at hand. Consider the first script shown in this chapter, the one designed to map a network drive on the local computer: Set objnetwork = CreateObject("WScript.Network") objnetwork.mapnetworkdrive "X:", "\\atl-fs-01\public" This script is about as simple as it can be, which is exactly the point: You do not have to study it very long before you say to yourself, "Oh, so thats how I map network drives using a script." Admittedly, in a production environment you might want to modify the script so that the user can specify any drive letter and any shared folder. This can be done, but you will need code for parsing command-line arguments. Likewise, the sample script will fail if drive X is already mapped to a shared folder. This can be accounted for too, but now you need code to check which drive letters are in use and then to prompt the user to enter a new drive letter. You might also need code that checks to make sure that the shared folder \\atl-fs-01\public actually exists. To account for all these activities would turn a 2-line script into a 22-line script; even worse, the whole idea of showing the script in the first place demonstrating how to map network drives would then be buried somewhere in the middle of a relatively large script. Keeping the scripts short and simple also drives home the point that scripts do not have to be complicated to be useful. If you are creating a script that will be used by many different people throughout your organization, it might be advisable to include argument parsing and error handling. But what if this is a script that only you will use? In this case, you may not need these features. You should never feel compelled to do something in a script just because someone else did it that way. The only thing that matters is that the script carries out its appointed task. A Note Regarding VBScript All the scripts in this book were written using VBScript. The decision to use VBScript rather than another scripting language or combination of languages was based on three factors: With the possible exception of Perl, VBScript is the most popular language used for writing system administration scripts. It made sense to choose a language that many people are at least somewhat familiar with. Unlike Perl, VBScript (along with Jscript) is automatically installed on all Windows 2000based computers. Thus there is nothing to buy and nothing to install. VBScript is easier to learn than Jscript. As a sort of added bonus, VBScript is very similar to Visual Basic, a programming language that many system administrators have a nodding acquaintance with. In other words, VBScript is easy to use, requires no additional purchase, download, or installation, and has a large user base. This makes it ideal for introducing people to system administration scripting. To be honest, though, in many ways the scripting language is irrelevant. By itself, VBScript offers very little support for system administration; VBScript is most useful when it works with WSH, WMI, ADSI, and other 10 Introduction to Windows Script Technologies

Introduction to Windows Script Technologies 11 scripting technologies that offer extensive support for system administration. In this respect, it is similar to other scripting languages. The vast majority of the scripts in this book rely on WMI or ADSI; the scripting language is almost incidental. Do you prefer working in JScript or ActiveState ActivePerl? Great; all you have to do is learn how to connect to WMI or ADSI using those languages and then take it from there. For example, here is a WMI script that retrieves and then displays the name of the BIOS installed on the computer. This script is written in VBScript. strcomputer = "." Set objwmiservice = GetObject("winmgmts:\\ " _ & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery _ ("Select * from Win32_BIOS") For Each objitem in colitems Wscript.Echo objitem.name Next Here is the same script, written in JScript. As you can see, the syntax and language conventions are different, but the key elements (shown in boldface) connecting to WMI, retrieving information from the Win32_BIOS class, echoing the value of the BIOS name are almost identical. In that respect, the language is largely a matter of individual choice; you can use WMI and VBScript to retrieve BIOS information, or you can use WMI and JScript to retrieve BIOS information. var strcomputer = "."; var objwmiservice = GetObject("winmgmts:\\\\ " + strcomputer + "\\root\\cimv2"); var colitems = objwmiservice.execquery ("Select * from Win32_BIOS"); var e = new Enumerator(colItems); for (;!e.atend();e.movenext()) { var objitem = e.item(); WScript.Echo(objItem.Name); } Note In reality, there are some minor differences among scripting languages that affect what you can and cannot do with system administration scripts. However, these differences are not important to this discussion. System Requirements This book is targeted toward computers running any Microsoft Windows 2000 operating system (including Microsoft Windows 2000 Professional, and Microsoft Windows 2000 Server, Windows 2000 Advanced Server, and Windows 2000 Datacenter Server). In addition to having Windows 2000 installed, these computers should be running Windows Script Host version 5.6, which was released after Windows 2000. Some of the scripts in the book rely on features found only in version 5.6. For more information about WSH version 5.6, see "WSH Primer" in this book. Note If you do not have WSH 5.6, an installation file for Windows 2000 is included on the compact disc that accompanies this book. If your computer is running an operating system other than Windows 2000, see the Windows Script Technologies link on the Web Resources page at http://www.microsoft.com/windows/reskits/webresources and click the Microsoft Windows Script 5.6 download link. If you are not sure which version of WSH you have on your computer, see "WSH Primer" in this book for information about determining the WSH version number. Introduction to Windows Script Technologies 11

12 VBScript Overview If you are working with multiple operating systems, particularly Windows XP, it is also recommended that you install Windows 2000 Service Pack 2. Without this service pack, scripts running on a Windows 2000based computer are unable to retrieve information from a Windows XPbased computer (although the Windows XP computers can retrieve information from the Windows 2000 computers). In addition, most of these scripts require you to be logged on with administrative credentials; this is a requirement for most WMI and ADSI operations. If you want to run a script against a remote computer, you need to be an administrator both on your computer and on that local computer. Beyond that, no fancy scripting tools, editors, or integrated development environments (IDEs) are required. As long as you have Notepad installed, you are ready to start writing scripts. Send us your feedback VBScript Primer Microsoft Visual Basic Scripting Edition (VBScript) is an easy-to-use scripting language that enables system administrators to create powerful tools for managing their Microsoft Windows based computers. In the first half of this chapter, the fundamental principles of VBScript are illustrated by the creation of a simple script for determining the amount of free disk space on drive C of a computer. This script will evolve throughout the chapter into a more sophisticated tool, one that can determine the amount of free space for any drive on any computer. The second half of this chapter then explores these fundamental principles of VBScript programming in more detail and touches on other VBScript constructs of interest to system administrators. In This Chapter VBScript Overview VBScript Reference Send us your feedback VBScript Overview Microsoft Visual Basic Scripting Edition (VBScript) is often dismissed as being "just" a scripting language, the implication being that a scripting language is of little use to a system administrator faced with managing hundreds or even thousands of computers in an enterprise setting. Yet nothing could be further from the truth; when used in combination with technologies such as Windows Script Host (WSH), Windows Management Instrumentation (WMI), and Active Directory Service Interfaces (ASDI), VBScript becomes a powerful language for creating system administration tools. For example, using VBScript in combination with WMI and ADSI, you can write a script of 10,000 or so lines, complete with error handling, subroutines, and other advanced programming constructs. That single script can give you complete control over many aspects 12 VBScript Overview

Working with Objects 13 of your computing environment. But what makes VBScript such a useful tool for system administrators is that you do not have to create such elaborate and complicated solutions. You can instead spend a few minutes typing a handful of lines of code into Notepad, and instantly create a custom solution to a particular problem. For example, the three-line script in Listing 2.1 tells you how much free disk space is available on drive C of your computer. Listing 2.1 Retrieving Free Disk Space Using VBScript 1 2 3 Set objwmiservice = GetObject("winmgmts:") Set objlogicaldisk = objwmiservice.get("win32_logicaldisk.deviceid='c:'") Wscript.Echo objlogicaldisk.freespace If you have been having problems with users filling up drive C on their computers, you now have a custom solution for identifying the computers running low on disk space, a solution developed using nothing more sophisticated than Notepad. Of course, it might be that this script does not fully address your needs. For example, the script tells you the free space available only on your local computer; it cannot tell you how much free space is available on a remote computer. Likewise, the script reports the free space available only on drive C; it tells you nothing about free space available on drives D or E. But if the script does not fully meet your needs, it can easily be modified, and without starting from scratch. This is another advantage of scripting in general and VBScript in particular: You can start with a very simple script and add to it as your needs change and as you become more proficient with the language. This chapter illustrates this process. It begins with the script shown in Listing 2.1, which reports the amount of free disk space on drive C. Subsequent sections in the chapter will take this simple three-line script and gradually add functionality to make it more useful in more situations. When this series of enhancements is complete, you will have a script that can: Retrieve free disk space information for any computer in your organization, including remote computers. Retrieve free disk space information from multiple computers. Retrieve free disk space information for all drives installed in a computer. Issue a notification only if a drive is low on disk space. Continue to function if a user types an invalid computer name, or if a computer is not available over the network. As new features are added to the script, the VBScript constructs required to add this functionality are briefly explained. After the script has been completed, a reference section will cover these constructs (and others) in more detail. Send us your feedback Working with Objects VBScript allows system administrators to create complex scripts using such advanced programming capabilities as branching, looping, error handling, and the calling of functions and subroutines. It does not, Working with Objects 13

14 Connecting to Objects however, include intrinsic methods for performing system administration tasks. VBScript has built-in functions for determining the square root of a number or the ASCII value of a character, but no built-in methods for stopping services, retrieving events from event logs, or carrying out other tasks of interest to system administrators. Fortunately, there are other ways to programmatically perform these tasks, primarily through the use of Automation objects. Automation objects are a subset of COM (Component Object Model), a standard way for applications (.exe files) or programming libraries (.dll files) to present their functionality as a series of objects. In turn, programmers (or script writers) can use these objects, and the functionality of the application or programming library, in their own projects. For example, a word processing application might expose its spell checker as an Automation object, thus providing a way for script writers to add spell checking to their projects. The ability to work with Automation objects and to utilize the properties and methods of these objects makes VBScript a powerful tool for system administration. Admittedly, VBScript alone cannot read events from an event log; however, VBScript can use the functionality included within WMI to retrieve such events. VBScript has no intrinsic methods for creating user accounts; however, the language can use the functionality in ADSI to create such accounts. In fact, VBScript is often referred to as a glue language because one of its primary uses is to "glue" objects together. Rather than provide a seemingly infinite number of intrinsic functions devoted to system administration, VBScript instead provides a framework for using the methods and properties of Automation objects designed to carry out these tasks. For example, the script in Listing 2.2 illustrates the importance of Automation objects within VBScript. This script reports the amount of free disk on drive C of the local computer. Furthermore, it does this using very little VBScript code. Instead, the script: 1. Connects to WMI (an Automation object) by using the VBScript GetObject method. 2. Uses the WMI Get method to retrieve information about drive C. 3. Uses the WSH Echo method to report the amount of free disk space on drive C. As noted, there is very little VBScript code here. Instead, the primary purpose of VBScript in this example is to glue together the functionality of WMI and WSH. Listing 2.2 Using Objects in VBScript 1 2 3 Set objwmiservice = GetObject("winmgmts:") Set objlogicaldisk = objwmiservice.get("win32_logicaldisk.deviceid='c:'") Wscript.Echo objlogicaldisk.freespace Send us your feedback Connecting to Objects Before you can do anything with the data in a database, you must first make a connection of some kind to that database. Likewise, before you can do anything with the methods or properties of an Automation object, you must first make a connection to that object, a process known as binding. Binding to objects can be confusing, because VBScript and WSH both provide a GetObject and a CreateObject method for accessing objects. Furthermore, although the implementations are similar, there are 14 Connecting to Objects

Creating an Object Reference 15 some subtle differences that grow in importance as you become more proficient in scripting. These differences are discussed in more detail later in this chapter. For now, use the following rules-of-thumb without worrying about whether you are using the VBScript or the WSH method (although in most cases you will use the VBScript implementation): Use GetObject to bind to either WMI or ADSI. Both WMI and ADSI allow you to use a moniker when binding from VBScript. A moniker (discussed later in this chapter) is an intermediary object that makes it easy to bind to objects that do not exist in the file system namespace. ADSI exists in the Active Directory namespace, while WMI exists in its own namespace. Although it is possible (and sometimes required) to bind to WMI or ADSI using CreateObject, using GetObject and a moniker is typically faster and easier. Use CreateObject to bind to all objects other than WMI or ADSI. In general, CreateObject will be required to create new instances of such elements as the FileSystem object, the Dictionary object, and Internet Explorer. This is not a hard-and-fast rule, however. For example, you will often need to use CreateObject to create WMI objects other than SWbemServices (such as SWbemLocator). Connecting to WSH In line 1 of the script in Listing 2.2, the script binds to WMI by using the following code statement: Set objwmiservice = GetObject("winmgmts:") This connects the script to the WMI SWbemServices object. No similar binding string is used to connect to WSH. Instead, the Echo method is called without first binding to WSH. You are already connected to WSH because WSH is required to run a script written in VBScript. Send us your feedback Creating an Object Reference With Automation, you do not work directly with an object itself. Instead, you create a reference to the object by using GetObject or CreateObject and then assign this reference to a variable. After the reference has been created, you can access the methods and properties of the object by using the variable rather than the object itself. In the script in Listing 2.2, the GetObject method is used to assign the WMI SWbemServices object to the variable objwmiservice. After the assignment has been made, all the properties of the SWbemServices object can be accessed through objwmiservice. For example, in line 2 of the script, the Get method is used to retrieve the properties for drive C. Anytime you create an object reference, you must use the Set keyword when assigning the reference to a variable. For example, the following line of code will result in a run-time error: objwmiservice = GetObject("winmgmts:") To create the object reference, you must use the Set keyword like this: Set objwmiservice = GetObject("winmgmts:") Creating an Object Reference 15

16 Calling Methods Set is a special VBScript statement that is used only when creating an object reference. If you use Set for other purposes, such as assigning a value to a variable, a run-time error will occur. For example, this line of code will fail because no object named 5 can be found on the computer: Set x = 5 Send us your feedback Calling Methods Automation objects allow you to use their capabilities within your scripts. This enables you to create more powerful and more useful scripts than you could create if you were restricted to the functionality of the scripting language. For example, it is impossible to draw a chart or graph by using VBScript alone. Through Automation, however, you can borrow the capabilities of Microsoft Excel and easily add a chart or graph to, say, a Web page. Automation objects typically expose both methods and properties. (However, there is no requirement for them to expose either.) Methods are equivalent to the actions that the object can perform. For example, although the script in Listing 2.2 is only three lines long, it uses Automation to access the methods of two different COM objects and thus performs two different actions. These two methods are: The Get method, available through the WMI SWbemServices object. This method retrieves information for the specified object. The Echo method, available through the WSH WScript object. This method displays information on the screen. If a script is running in a command window and thus under CScript.exe, this information is displayed within that command window. If the script is running under Wscript.exe, the information is displayed in a message box. After you have created a reference to an object, you can call the methods of that object using dot notation. Dot notation is so named because you call a method by typing the name of the variable that references the object, a period (or dot), and the name of the method. (Depending on the method, you might also type method parameters.) Generally, dot notation uses the following syntax: ObjectReference.MethodName For example, in the following line of code, the SWbemServices Get method call is written in dot notation. Set objlogicaldisk = objwmiservice.get("win32_logicaldisk.deviceid='c:'") The parts of the SWbemServices Get method call are shown in Table 2.1. Table 2.1 Parts of the SWbemServices Get Method Call ObjWMIService Item Object reference. Description. Dot (separates the object reference and the name of the method). Get Method name. ("Win32_LogicalDisk.DeviceID=c:") Method parameter. For the Get method, this can be read as, "Get the 16 Calling Methods

Variables 17 Note instance of the Win32_LogicalDisk class where the DeviceID is equal to C:." Instead of using Wscript.Echo to display the amount of free disk space, you can use the VBScript function Msgbox: Msgbox objlogicaldisk.freespace In this book, however, Wscript.Echo is used instead of Msgbox. This is because the Msgbox function always displays its information in a graphical dialog box. When this dialog box appears, the OK button must be clicked before the script can proceed. For system administration scripts that display a large amount of data, this would be extremely tedious; it would also prevent the script from running automatically. By contrast, Wscript.Echo displays information as lines within a command window, provided the script is running under CScript. Send us your feedback Retrieving Properties Properties are the attributes associated with an object. They are particularly important in system administration scripting because many of the objects you use are virtual representations of actual objects. For example, in line 3 of Listing 2.2, the FreeSpace property is retrieved, using the same dot notation used to call methods. objlogicaldisk.freespace With WMI, this object reference refers not to some amorphous programming construct but to an actual hard disk within the computer. The FreeSpace property is thus not just a property of an Automation object but also of drive C. In a sense, WMI creates a virtual mirror of an actual physical object. When you retrieve the properties of that virtual mirror, you also retrieve the properties of the physical object. Send us your feedback Variables The script in Listing 2.2 works exactly as expected. When run, it reports the amount of free disk space on drive C. That does not mean that the script cannot be improved, however. For example, the FreeSpace property reports the number of bytes available on a drive. Because disk drive space is typically reported in gigabytes, the FreeSpace property often returns a value that is difficult to interpret. For example, Figure 2.1 shows the value reported for a drive with approximately 10 gigabytes of free disk space. Figure 2.1 Free Disk Space Expressed in Bytes Free Disk Space Expressed in Bytes Variables 17