Cover

Table of Contents

Cover

Title Page

Copyright

About the Authors

About the Technical Editor

Credits

Acknowledgments

Introduction

Who Should Read This Book

How This Book Is Organized

What’s on the Companion Web site

What You’ll Learn from This Book

Part I: Getting Started with Windows Scripting

Chapter 1: Introducing Windows scripting

Introducing Windows Scripting

Windows Script Host Architecture

Windows PowerShell Architecture

Summary

Chapter 2: VBScript Essentials

Working with Variables

Working with Constants

Working with Arrays

VBScript Operators

Conditional Statements

Control Loops

Using Procedures

Summary

Chapter 3: JScript Essentials

Variables and Data Types

Using Strings

Using Comments

Using Arrays

JScript Operators

Conditional Statements

Control Flow with Looping

Using Functions

Summary

Chapter 4: PowerShell Fundamentals

Shell Fundamentals

PowerShell Aliases

Cmdlets, Snap-ins, and Providers

Functions and Filters

Objects and Types and the PowerShell Pipe

Exploring PowerShell Variables

Richer Types and .NET Objects

Arrays

The PowerShell Pipe

Looping in PowerShell

Conditions

Scripts, Script Blocks, and Functions

Scripts and Security

Summary

Part II: Windows VBScript and JScript

Chapter 5: Creating Scripts and Scripting Files

Running Scripts

Creating Batch Scripts

Summary

Chapter 6: VBScript and JScript Scripting Basics

Key WSH Objects

Displaying Text Strings

Examining Script Information

Working with Environment Variables

Running Programs from Within Scripts

Running Scripts Remotely

Combining JScript and VBScript

Summary

Chapter 7: Input, Output, and Error Handling with VBScript and JScript

Input and Output Essentials

Using Input Boxes

Using Message Boxes

Error Detection and Handling

Summary

Chapter 8: Working with Files and Folders in VBScript and JScript

Understanding the FileSystemObject

Working with Folders

Using Special Folders

Working with Files

Summary

Chapter 9: Reading and Writing Files

Opening Files

Reading Text Files

Skipping Lines in a File

Writing to a File

Summary

Chapter 10: Managing Drives and Printers with VBScript and JScript

Managing Drives

Obtaining Drive Information

Mapping Network Drives

Managing Network Printers

Summary

Chapter 11: Configuring Menus, Shortcuts, and Startup Applications

Working with Menus, Desktops, and Startup Applications

Creating Shortcuts and Menu Options

Managing Shortcuts and Menus

Adding and Removing Startup Applications

Summary

Chapter 12: Working with the Windows Registry and Event Logs

Working with the Windows Registry

Using Event Logs

Writing to Event Logs

Reading Event Logs

Generating Event Log Reports

Summary

Part III: Network and Directory Service Scripting

Chapter 13: Scheduling One-time and Recurring Tasks

Scheduling Local and Remote Jobs

Using the Graphical Task Scheduler

Scheduling Jobs with AT

Scheduling with Scripts

Summary

Chapter 14: Managing Computer and User Scripts

Why Use Computer and User Scripts?

Introducing Group Policies

Working with Computer and User Scripts

Summary

Chapter 15: Introducing Active Directory Services Interfaces

ADSI Essentials

Taking Advantage of ADSI

ADSI Provider Basics

Summary

Chapter 16: Using Schema to Master ADSI

Exploring ADSI Schema

Working with Schema Class Objects

Viewing Property Syntax, Ranges, and Values

Summary

Chapter 17: Managing Local and Domain Resources with ADSI

Managing Domain Account Policies

Working with Local Computer Properties

Creating and Modifying User Accounts

Creating and Modifying Group Accounts

Summary

Chapter 18: Service and Resource Administration with ADSI

Managing Windows Services

Checking Service Status and Dependencies

Viewing and Setting Service Information

Starting, Stopping, and Pausing Services

Managing Open Resources and User Sessions

Summary

Chapter 19: Maintaining Shared Directories, Printer Queues, and Print Jobs

Working with Shared Folders

Managing Print Queues

Controlling Print Jobs

Summary

Chapter 20: Managing Active Directory Domain Extensions

Working with Naming Contexts and the RootDSE Object

Accessing Active Directory Schema

Managing Computer Objects with LDAP

Managing Contacts with LDAP

Managing Groups with LDAP

Working with Organizational Units

Managing User Accounts with LDAP

Summary

Part IV: Windows PowerShell

Chapter 21: Input, Output, and Error Handling in PowerShell

Output to the Console

A Little Diversion into Strings

Implicit and Explicit Output

Verbose and Debug Output

Managing Different Outputs from Cmdlets

More on Error Output

Session Transcripts

Tracking Progress

Taking More Control of Formatting

Sorting and Selecting Fields

Changing How PowerShell Formats Objects

Creating Custom Objects on Demand

Techniques for Switching in Output

Additional Output Cmdlets

Outputting in Specific File Formats

Every Export Has a Corresponding Import

More on Selecting Text

User Input

Summary

Chapter 22: Working with Files and the Registry in PowerShell

Using PSDrives, Accessing the File System, Mapping Drives

Summary

Chapter 23: Event Logging, Services, and Process Monitoring with PowerShell

Working with Services

Starting, Stopping, Suspending, Resuming, and Restarting Services

Working with Processes

Working with Event Logs

Summary

Chapter 24: Working with Active Directory Using ADSI and PowerShell

A Quick Introduction to Active Directory

Getting Entries from AD with [ADSI]

Creating Objects

Getting Directory Entries with the Searcher

Operations on Directory Entries

Summary

Chapter 25: Working with WMI in PowerShell

Displaying WMI Information

Querying WMI

Querying Across Computers

Discovering WMI Objects

WMI Object Properties

Updating WMI Objects

WMI Object Methods

A Case Study for WMI: Server 2008 Hyper-V

Summary

Part V: Windows Scripting Libraries

Chapter 26: Library: File-System Utilities

Examining the File-System Utility Library

Using the File-System Utility Library

Summary

Chapter 27: Library: I/O Utilities

Examining the I/O Utility Library

Using the I/O Utility Library

Summary

Chapter 28: Library: Network Resource Utilities

Examining the Network Resource Utility Library

Using the Network Resource Utility Library

Summary

Chapter 29: Library: Account Management Utilities

Building the Account Management Library

Using the Account Management Utilities

Summary

Chapter 30: Library: Building a PowerShell Library

Customizing Your PowerShell Environment

A Generic “choose” Function

Network Utilities

Clever Uses for Hash Tables

COM Objects: A Firewall Tool

Using .NET Objects to Access Mail and Web Services

Regular Expressions

More Advanced Text Processing—Discovering Script Dependencies

Scripts or Fuctions: Checking How a Script Was Invoked

Summary

Part VI: Appendixes

Appendix 1: Windows Scripting API

XML Elements

getResource Static Method

Drives Collection

Printers Collection

StdIn Stream*

StdErr Stream*

StdOut Stream*

WshArguments Collection

WshNamed Collection

WshUnnamed Collection

Script.Signer Object

WScript Object

WshController Object

WshEnvironment Object

WshNetwork Object

WshRemote Object

WshRemoteError Object

WshScriptExec Object

WshShell Object

WshShortcut Object

WshSpecialFolders Object

WshUrlShortcut Object

Appendix 2: Core ADSI Reference

Using This Reference

ADSI Interfaces

ADSI Error Codes

Appendix 3: Essential Command-Line Utilities for Use with WSH

ARP

ASSOC

AT

ATTRIB

CACLS

CHKDSK

COMPACT

CONVERT

DATE

DRIVERQUERY

EXPAND

FC

FORMAT

FTP

FTYPE

IPCONFIG

NBTSTAT

NET ACCOUNTS

NET COMPUTER

NET CONFIG SERVER

NET CONFIG WORKSTATION

NET CONTINUE

NET FILE

NET GROUP

NET LOCALGROUP

NET PAUSE

NET PRINT

NET SESSION

NET SHARE

NET START

NET STATISTICS

NET STOP

NET TIME

NET USE

NET USER

NET VIEW

NETSTAT

NSLOOKUP

PATH

PING

RECOVER

ROUTE

SCHTASKS

TIME

TRACERT

Index

Advertisement

Title Page

About the Authors

William R. Stanek (http://www.williamstanek.com/) has over 20 years of hands-on experience with advanced programming and development. He is a leading technology expert, an award-winning author, and a pretty-darn-good instructional trainer. Over the years, his practical advice has helped millions of technical professionals all over the world. He has written more than 75 books, including Microsoft Exchange Server 2007 Administrator’s Pocket Consultant, Microsoft Windows Vista Administrator’s Pocket Consultant, Microsoft Windows Server 2008 Administrator’s Pocket Consultant, and Windows Server 2008 Inside Out.

Mr. Stanek has been involved in the commercial Internet community since 1991. His core business and technology experience comes from over 11 years of military service. He has substantial experience in developing server technology, encryption, and Internet solutions. He has written many technical white papers and training courses on a wide variety of topics. He frequently serves as a subject matter expert and consultant.

Mr. Stanek has an MS with distinction in information systems and a BS magna cum laude in computer science. He is proud to have served in the Persian Gulf War as a combat crewmember on an electronic warfare aircraft. He flew on numerous combat missions into Iraq and was awarded nine medals for his wartime service, including one of the United States of America’s highest flying honors, the Air Force Distinguished Flying Cross. Currently, he resides in the Pacific Northwest with his wife and children.

James O’Neill was born in 1965, used his first Microsoft product at the age of 13, and has scarcely stopped since. He describes himself as a compulsive explainer, which led him to work as a technical trainer and run a small training company in the 1990s. He joined Microsoft Consulting Services in 2000, and after six years there working with a wide variety of clients he moved back to a role where he can explain more, becoming an evangelist, talking to IT professionals primarily about Windows platform technologies. He is a veteran of every Microsoft operating system and network technology since DOS 3.1 MS-Net and Windows 1.03, and has used a dozen or so programming and scripting languages. Over the last two years, he has become increasingly evangelical about PowerShell, using it to write libraries that support Windows 2008 virtualization and Office Communications Server. He lives near Oxford, England with his wife and two children, and occasionally manages to find time for photography and scuba diving. He has a worrying tendency to write about himself in the third person.

Jeffrey Rosen has a Masters of Business Administration from Case Western Reserve, Weatherhead School of Management, specializing in Information Systems. He is a Microsoft Certified Architect, an MCSE specializing in messaging and security, and a CISSP. He began his career working with Microsoft Mail and Novell Netware. Since then, Jeffrey has worked for Microsoft Consulting Services for nine years on large and complex Exchange deployments. He is a co-author of Professional PowerShell for Exchange 2007 SP1.

About the Technical Editor

Andrew Edney has been an IT professional for more than 12 years and has, over the course of his career, worked for a range of high-tech companies, such as Microsoft, Hewlett-Packard, and Fujitsu Services. He has a wide range of experience in virtually all aspects of Microsoft’s computing solutions, having designed and architected large enterprise solutions for government and private-sector customers. Over the years, Andrew has made a number of guest appearances at major industry events, presenting on a wide range of information systems subjects, such as an appearance at the annual Microsoft Exchange Conference in Nice where he addressed the Microsoft technical community on mobility computing. Andrew is currently involved in numerous Microsoft beta programs, including next-generation Windows operating systems and next-generation Microsoft Office products. He actively participates in all Windows Media Center beta programs and was heavily involved in the Windows Home Server beta program. In addition, Andrew has written a number of books including: Windows Home Server User’s Guide (2007), Pro LCS: Live Communications Server Administration ( 2007), Getting More from Your Microsoft Xbox 360 (2006), How to Set Up Your Home or Small Business Network (2006), Using Microsoft Windows XP Media Center 2005 (2006), Windows Vista: An Ultimate Guide (2007), PowerPoint 2007 in Easy Steps (2007), Windows Vista Media Center in Easy Steps (2007), and Using Ubuntu Linux (2007).

Credits

Acquisitions Editor

Katie Mohr

Development Editor

Ed Connor

Technical Editor

Andrew Edney

Production Editor

Melissa Lopez

Copy Editor

Nancy Rapoport

Editorial Manager

Mary Beth Wakefield

Production Manager

Tim Tate

Vice President andExecutive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Barry Pruett

Associate Publisher

Jim Minatel

Compositor

James D. Kramer, Happenstance Type-O-Rama

Proofreaders

Corina Copp and Sheilah Ledwidge

Indexer

Jack Lewis

Cover Image

Joyce Haughey

Cover Designer

Michael E. Trent

Acknowledgments

Writing PowerShell, VBScript, and JScript Bible took a lot of work and research. Much of the time was spent searching for undocumented features, resolving problems with poorly documented interfaces, and exploring uncharted areas of Windows. Then, I had to write about the hidden features and the many interfaces I had discovered. I hope you’ll agree that the result was worth all of the effort. The book contains over 300 code examples and dozens of working scripts, all designed to provide a top-notch tutorial and reference.

PowerShell, VBScript, and JScript Bible wouldn’t have been possible without a lot of help from others and, especially, the team at Wiley: Katie Mohr, the Acquisitions Editor, and Ed Connor, the Development Editor.

A big thank you goes out to my close contacts and friends at Microsoft. Thanks also to Studio B literary agency and my agents, David Rogelberg and Neil Salkind. Neil has a terrific knack for helping me find projects that are both fun and challenging.

I hope I haven’t forgotten anyone, but if I have, it was an oversight. Honest. ;-)

William R. Stanek

There are a few people without whom I wouldn’t have been able to contribute to this book. Neil Salkind at Studio B who asked is perhaps first in the queue to be thanked. Richard Siddaway, who started the first PowerShell user group, is probably the person most responsible for the depth of my interest in the subject. At Microsoft, I should mention Jeffrey Snover for his encouragement and Eileen Brown, my manager but also my friend, mentor, and when I least deserve it, my advocate. She deserves far greater thanks than a mention here. And finally, my family: my wife, Jackie, and my children, Lisa and Paul. Kids: the book in your hands is one of the reasons why Daddy kept asking you to be quiet.

James O’Neill

To my wife, Christine, and our daughters, Madison and Isabel, I love you, and thanks for always being there for me. Also, thanks to the authors, editors, and other invaluable staff that I’ve had the pleasure of working with.

Jeffrey Rosen

If you’ve purchased PowerShell, VBScript, and JScript Bible or are thumbing through the book in a bookstore somewhere, you probably want to know how this book can help you. Our goal in writing PowerShell, VBScript, and JScript Bible is to create the best resource available on scripting the Windows operating system.

As you’ll learn in this book, Windows scripting involves many different technologies. These technologies include:

We’ve tried to pack in as much information about these topics as possible, and to present the information in a way that is both clear and concise. We’ve also tried to present Windows scripting in a unique way, offering both VBScript and JScript solutions throughout the text and then discussing how to accomplish similar tasks using PowerShell. In this way, you can learn exactly how VBScript, JScript, and PowerShell can be used with Windows. With this approach, you gain insight into unique scripting techniques necessary to implement solutions in VBScript, JScript, and PowerShell, and, if you prefer one technique over the other, there’s no more guesswork.

Introduction

PowerShell, VBScript, and JScript Bible is a work in progress, just like the Windows operating system itself and the body of work that’s grown up around it. It is quite likely that errors will make themselves apparent after this book has gone to press and found its way onto your desktop. I very much appreciate the efforts of readers who go to the trouble of pointing out mistakes in the text so I can fix them in future editions. Even more, I am grateful for readers who offer their own hints, tricks, code, and ideas to me for inclusion in future editions of this book.

I truly hope you find that PowerShell, VBScript and JScript Bible provides everything you need to perform essential scripting tasks. You can contact me through e-mail at williamstanek@aol.com. You’re always welcome to write me with ideas, suggestions, improvements, or questions. If you provide an example that’s used in a future edition of this book, I’ll be especially grateful for your help and will credit you in that edition. I also have a Web site, which contains support material for this book, among other things. Point your browser to www.williamstanek.com/scripting/ for corrections, enhancements, news, and additional thoughts. I’ll post the source code from this book as well.

Thank you!

William R. Stanek

The best introduction to a book I ever saw was from Machiavelli’s The Discourses, where he says something like, “I’m sending you something, and if it doesn’t meet the obligations I owe you, is at any rate the best I can send. For in it I have set down all I know from long experience and constant reading…you may perhaps lament my lack of skill should my narratives be thin and also errors of judgment if I have made mistakes.”

The longer the piece that I write, the more likely I am to think of that. The experience I have in PowerShell builds on decades of seeing different scenarios and using different tools: and that experience has been gained working with people who don’t think of themselves as Programmers. Graphical management tools make it easy to find how to do a one-off task, but some repetitive tasks aren’t efficient with the GUI. Some information can’t be extracted easily from a graphical tool: some tasks just weren’t anticipated by the Programmer who wrote it. UNIX system administrators have known for a long time that there is an area, which isn’t Programming in the customary sense, of creating a large beast, with considerations such as user interface design to be taken into account. It produces something that a dictionary would define as a program—a sequence of instructions to be followed by the computer. A script is a program but not a Program (the capitalization is deliberate). Scripts are written mostly by people who are not Programmers, but just know the job they need to get done. And, usually a script will involve less time to create than a “proper” Program and will pay back the time that went into it very quickly. Want to know which of the servers you manage don’t have a key patch on them—without logging onto each one? It’s a few lines of script; a system administrator can put it together in a couple of minutes. A Programmer (capital P) won’t have fired up Visual Studio and roughed out the user interface in that time.

Better still for the Windows system administrator, most of the work has been done by someone else. Want a list of your servers? A couple of lines of script will get it from Active Directory. Want the installed patches on each of those servers? One line of PowerShell will get that. Most of the knowledge needed isn’t of a programming or scripting language—whether you use PowerShell, VBScript, or any other environment, it is a question of understanding the task and the objects that you can call on from that environment. PowerShell has all of .NET, WMI, AD, and ActiveX/COM at its disposal. It needs a whole bookshelf to explain all of those things, so what we do in this book is to try to equip you, the reader, with the skills you need to use them—which is why I worry that my narratives may be thin.

Who Should Read This Book

If you are someone who is interested in any of the previously mentioned technologies, PowerShell, VBScript and JScript Bible is definitely a book you should read. This comes with several caveats. This book is designed for:

To pack in as much information as possible, We had to assume that you have basic networking skills, a basic understanding of Windows, and that Windows is already installed on your systems. With this in mind, we don’t devote entire chapters to understanding, installing, or using Windows. Beyond the introductory information in Chapters 1, 2, and 3, we don’t cover scripting basics either. We do, however, cover every facet of Windows scripting, so if you want to learn Windows scripting inside and out—including techniques not published elsewhere—you’ve come to the right source.

Although the book highlights the latest and greatest features of Windows Vista and Windows Server 2008, just about everything you learn in this book can also be applied to script Windows XP. Keep in mind that if you are using a pre–Windows Vista system, however, you may need to check your scripts to ensure they are fully compatible.

How This Book Is Organized

Learn the basics of what goes into Windows and you will be able to use all sorts of devices and computers in the future. The book is organized in a way that enables you to start off at the very beginning with Windows, but still grow to the point where you can get going with some powerful server and programming features, if you care to.

Part I assumes that someone has set up a Windows system in front of you. After being introduced to Windows script in Chapter 1, you learn the basics of how to:

In Part II, you learn how to:

In Part III, you learn network and directory service scripting:

In Part IV, you learn Windows PowerShell:

In Part V, you develop a set of programming libraries:

In Part VI, you’ll learn more about:

Conventions and Features

As with most computer books, you’ll see that some text is highlighted by special formatting or with special icons. Here’s a field guide to the things you’ll see.

note.eps

Notes provide additional details and often contain information that you should read before trying to implement a referenced technique.

cross_ref.eps

Cross-references tell you where you can find more information on a particular topic.

tip.eps

Tips inform you of little factoids that may be useful to you as you work with Windows scripting. Tips provide helpful information that isn’t always essential to getting things to work correctly. Rather, Tip material can be used to make things run better.

caution.eps

Cautions provide a specific warning about things you should watch out for, or things you shouldn’t do. You should pay particular attention to Cautions when reading the text.

Source-Code Formatting

The text contains source-code listings as well as in-text references to objects, methods, properties, and other source-code elements. In order to minimize line wrapping and formatting issues, we generally use in-line code lists for code examples. For example:

VBScript

Setfs=CreateObject("Scripting.FileSystemObject")

Setf=fs.OpenTextFile(aFile,ForAppending)

f.WriteLinetheLine

f.Close

JScript

varfs=newActiveXObject("Scripting.FileSystemObject");

varf=fs.OpenTextFile(aFile,ForAppending)

f.WriteLine(theLine)

f.Close()

In-text references to source-code elements are highlighted with a monospace font, as in the following sentence. The OpenTextFile method is used to open text files. Don’t confuse monospace type with in-text elements printed in bold. When you see bold text in the middle of a paragraph, it means that this is something you should type in at the keyboard, such as, “Type cls at the command prompt to clear the screen.”

What’s on the Companion Web site

On the companion Web site, you will find the following:

What You’ll Learn from This Book

Every how-to book is supposed to teach its readers how to do something, and in the process convey some body of knowledge to the reader. PowerShell, VBScript and JScript Bible is no exception. This book teaches you about Windows scripting and includes in-depth coverage of related technologies.

PowerShell, VBScript and JScript Bible isn’t meant to be a do-everything guide to scripting. Rather, the book focuses on techniques you’ll use to script the Windows operating system. Chapter by chapter, you learn how to create scripts. The detailed explanations provided are backed by hundreds of hands-on examples and over 300 complete source-code listings. This book also develops extensive utility libraries that you can use to quickly and efficiently perform complex tasks.

Part I

Getting Started with Windows Scripting

In This Part

Chapter 1: Introducing Windows Scripting

Chapter 2: VBScript Essentials

Chapter 3: JScript Essentials

Chapter 4: PowerShell Fundamentals

Part I of the PowerShell, VBScript, and JScript Bible introduces you to the powerful administrative tool that is Windows scripting. You’ll get an overview of Windows scripting and its potential, and an introduction to three technologies you can use for Windows scripting: VBScript, JScript, and PowerShell.