46,99 €
Packed with more than 300 sample scripts and an extensive collection of library functions, this essential scripting book is the most thorough guide to Windows scripting and PowerShell on the market. You'll examine how Windows scripting is changing the face of system and network administration by giving everyday users, developers, and administrators the ability to automate repetitive tasks. Plus, this is the first time that VBScript, Jscript, and Powershell are all covered in a single resource.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1002
Veröffentlichungsjahr: 2011
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
Microsoft® PowerShell, VBScript, and JScript® Bible
Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256www.wiley.com
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-38680-4
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data is available from the publisher.
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Microsoft and JScript are registered trademarks of Microsoft Corporation in the United States and/or other countries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
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:
Windows operating systemsWindows Script Host (WSH)Scripting languages, such as VBScript and JScriptWindows PowerShellActiveX and COM (Component Object Model) componentsMicrosoft Active DirectoryADSI (Active Directory Services Interfaces)WMI (Windows Management Instrumentation)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 [email protected]. 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:
Administrators who support Windows systemsDevelopers who create scripts or programs for Windows systemsAdvanced users working with Windows systemsTo 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:
VBScript Essentials (Chapter 2)JScript Essentials (Chapter 3)PowerShell Essentials (Chapter 4)In Part II, you learn how to:
Creating Scripts and Scripting Files (Chapter 5)VBScript and JScript Scripting Basics (Chapter 6)Input, Output, and Error Handling with VBScript and JScript (Chapter 7)Working with Files and Folders in VBscript and JScript (Chapter 8)Reading and Writing Files (Chapter 9)Managing Drives and Printers with VBScript and JScript (Chapter 10)Configuring Menus, Shortcusts, and Startup Applications (Chapter 11)Working with the Windows Registry and Event Logs (Chapter 12)In Part III, you learn network and directory service scripting:
Scheduling One-time and Recurring Tasks (Chapter 13)Managing Computer and User Scripts (Chapter 14)Introducing Active Directory Service Interfaces (Chapter 15)Using Schema to Master ADSI (Chapter 16)Managing Local and Domain Resources with ADSI (Chapter 17)Service and Resource Administration with ADSI (Chapter 18)Maintaining Shared Directories, Printer Queues, and Print Jobs (Chapter 19)Managing Active Directory Domain Extensions (Chapter 20)In Part IV, you learn Windows PowerShell:
Input, Output and Error Handling in PowerShell (Chapter 21)Working with Files and Registry in Powershell (Chapter 22)Event Logging, Services, and Process Monitoring with PowerShell (Chapter 23)Working with Active Directory Using ADSI and PowerShell (Chapter 24)Working with WMI and PowerShell (Chapter 25)In Part V, you develop a set of programming libraries:
Library: File-System Utilities (Chapter 26)Library: I/O Utilities (Chapter 27)Library: Network Resource Utilities (Chapter 28)Library: Account Management Utilities (Chapter 29)Library: Building a PowerShell Library (Chapter 30)In Part VI, you’ll learn more about:
Windows Scripting API (Appendix A)Core ADSI Reference (Appendix B)Essential Command-Line Utilities for Use with WSH (Appendix C)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.
Notes provide additional details and often contain information that you should read before trying to implement a referenced technique.
Cross-references tell you where you can find more information on a particular topic.
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.
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:
Sample code: Each chapter has its own subfolder on the Web site, and you will find all the code output that was discussed in each chapter organized accordingly.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.
Chapter 1
Introducing Windows Scripting
In This Chapter
Introducing Windows scriptingWhy script Windows?Getting to know Windows Script HostUnderstanding the Windows scripting architectureWindows scripting gives everyday users and administrators the ability to automate repetitive tasks, complete activities while away from the computer, and perform many other time-saving activities. Windows scripting accomplishes all of this by enabling you to create tools to automate tasks that would otherwise be handled manually, such as creating user accounts, generating log files, managing print queues, or examining system information. By eliminating manual processes, you can double, triple, or even quadruple your productivity and become more effective and efficient at your job. Best of all, scripts are easy to create and you can rapidly develop prototypes of applications, procedures, and utilities; and then enhance these prototypes to get exactly what you need, or just throw them away and begin again. This ease of use gives you the flexibility to create the kinds of tools you need without a lot of fuss.
Introducing Windows Scripting
You’ve heard the claims about scripting and now you’re thinking, so what? What’s in it for me? You may be an administrator rather than a developer. Or maybe you’re a power user who helps other users from time to time. Either way, scripting will prove useful to your situation and needs. So in answer to the question, “What’s in it for me?” consider the following:
Would you like to have more free time? Windows scripting frees you from mundane and repetitive tasks, enabling you to focus on more interesting and challenging tasks.Would you like to be able to analyze trends and be proactive rather than reactive? You can use Windows scripting to extract and manipulate huge quantities of information and turn out easy-to-use reports.Would you like to be able to seize opportunities before they disappear? Windows scripting enables you to take advantage of opportunities and be more effective. You can solve problems quickly and efficiently.Would you like to be a top performer and receive the praise you deserve? Windows scripting enables you to accomplish in hours or days what would otherwise take weeks or months with traditional techniques. You’ll be more successful and more productive at work.Would you like to be able to integrate activities and applications? Windows scripting enables you to integrate information from existing systems and applications, allowing you to kick off a series of tasks simply by starting a script.Would you like to have fun at work? Windows scripting can be fun, challenging, and rewarding. Give it a try and you’ll see!If Windows scripting can do so much, it must be terribly complex, right? On the contrary—it is its simplicity that enables you to do so much, not complexity. Many Windows scripts are only a few lines long and you can create them in a few minutes!
Taking a look at Windows Scripting
Two different architectures are used for scripting in Windows. The older one uses the Windows Script Host and the newer one uses PowerShell. A lot of the tasks that can be carried out using the VBScript in the Windows Scripting Host can be transferred to PowerShell. However not all the tasks that can be run in PowerShell can be transferred to Windows Script Host scripts so easily. For a lot of organizations using various derivatives of Visual Basic—in Web pages, Office applications, Windows forms applications—makes a de-facto standard.
Windows Script Host Architecture
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines—each of which is discussed in the sections that follow.
Getting Started with Windows Script Host
Windows Script Host is a core component of the Windows operating system and, as such, is installed by default when you install Windows. Like other components, Windows Script Host can be uninstalled. It can also be upgraded through downloads or by installing service packs. To ensure that Windows Script Host is installed on your system, type cscript at a command prompt. You should see version information for Windows Script Host as well as usage details. If you don’t see this information, Windows Script Host may not be installed and you’ll need to install it as you would any other Windows component.
The key components of Windows Script Host are as follows:
WScript: A Windows executable for the scripting host that is used when you execute scripts from the desktop. This executable has GUI controls for displaying output in pop-up dialog boxes.CScript: A command-line executable for the scripting host that is used when you execute scripts from the command line. This executable displays standard output at the command line.WSH ActiveX Control: An ActiveX control that provides the core object model for the scripting host.Scripting Engines: Scripting engines provide the core functions, objects, and methods for a particular scripting language. VBScript and JScript scripting engines are installed by default on Windows.A Windows script is a text file containing a series of commands. Unlike shell scripts, Windows script commands don’t resemble commands that you’d type in at the keyboard. Instead, they follow the syntax for the scripting language you are using, such as VBScript or JScript.
Windows scripts can be created in Notepad. When you finish creating the script, save it with an extension appropriate for the scripting language (.vbs for VBScript, .js for JScript, or .wsf for batch scripts that combine scripts with markup). Once you create a Windows script, you run it with WScript or CScript.
Using and running scripts
Windows scripts can be run with either WScript or CScript, and most of the time the application you use depends on your personal preference. However, you’ll find that WScript works best for scripts that interact with users, especially if the script displays results as standard text output. For tasks that you want to automate or run behind the scenes, you’ll probably prefer CScript, with which you can suppress output and prompts for batch processing.
You can use WScript and CScript with scripts in several different ways. The easiest way is to set WScript as the default application for scripts and then run scripts by clicking their file name in Windows Explorer. Don’t worry—you don’t have to do anything fancy to set WScript as the default. The first time you click a Windows script, you’ll be asked if you’d like to associate the file extension with WScript. Click Yes. Alternatively, you may see an Open With dialog box that asks which program you would like to use to open the file. Choose WScript, and then check the “Always use this program to open this file” checkbox.
You can also set CScript as the default interface. When you do this, clicking a Windows script runs CScript instead of WScript. Or, you could run scripts from the Run prompt just as you could when WScript was the default. To run scripts with CScript from the command line, enter cscript followed by the pathname of the script you want to execute. For now, don’t worry about the details; you’ll find detailed instructions in Chapter 4.
Core object model
The core object model and scripting hosts are packaged with WSH for Windows. The core object model is implemented in the WSH.ocx ActiveX control. WSH.ocx provides the key functionality necessary for scripts to interact with the operating system. In WSH, objects are simply named containers that you’ll use to interact with operating system components. For example, you’ll use the WshNetwork object to access and configure network resources, such as printers and drives.
Each object has properties and methods that are used to perform certain types of tasks. Properties are attributes of an object that you can access. Methods are procedures that you’ll use to perform operations. As with other object-based programming languages, you can work with objects in a variety of ways. You can use built-in objects, create new objects based on the built-in objects, or define your own objects using unique methods and properties.
Table 1-1 provides a summary of the WSH object model. The WSH object hierarchy can be broken down into two broad categories: exposed objects and non-exposed objects. Exposed objects, such as WScript, are the ones you’ll work with in your scripts. Non-exposed objects, such as WshCollection, are accessed through the methods or properties of other objects. These objects do the behind-the-scenes work.
Table 1-1: Core WSH Objects
Object TypeObjectDescription Exposed Object Script.Signer An object that allows you to sign scripts with a digital signature and to verify signed scripts WScript Top-level object that provides access to core objects and other functionality such as object creation WScript.WshNetwork Automation object used to access and configure network resources, such as printers and drives, also provides user, domain, and computer information WScript.WshShell Automation object that provides access to the environment and file folders WshController Automation object that provides the control functions necessary for creating a remote script process Non-exposed Object WshArguments Accessed through the WScript.Arguments property, obtains command-line arguments WshCollection Accessed through WshNetwork.EnumNetworkDrives or WshNetwork.EnumPrinterCollection, used for iteration through a group of items, such as printers or drives WshEnvironment Accessed through the WshShell.Environment property, allows you to work with environment variables WshNamed Accessed through the WScript.Arguments.Named property, allows you to work with named arguments passed to a script WshRemote Accessed through the WshController.WshRemote method, allows you to start, stop, and track the status of remote scripts WshRemote.Error Accessed through the WshRemote.Error property, used to track runtime errors related to remote scripts WshScriptExec Accessed through the WshShell.Exec method, allows you to track the status of program or scripts started with the WshShell.Exec method, also provides access to the related input, output, and error streams WshShortcut Accessed through the WshShell.CreateShortcut method, used to create and manage file shortcuts WshSpecialFolders Accessed through the WshShell.SpecialFolders property, used to work with file folders WshUnnamed Accessed through the WScript.Arguments.Unnamed property, allows you to work with unnamed arguments passed to a script WshUrlShortcut Accessed through the WshShell.CreateShortcut method, used to create and manage URL shortcutsWith the JScript scripting engine, the letter case for object, method, and property names is important. The JScript engine doesn’t recognize an object unless you reference it properly. For example, with WScript, the JScript engine does not recognize Wscript. Because VBScript really doesn’t care about letter case, either Wscript or WScript works just fine.
More on scripting hosts
To execute Windows scripts, you’ll use one of the two scripting hosts available, either WScript or CScript. WScript has GUI controls for displaying output in pop-up dialog boxes and is used primarily when you execute scripts from the desktop. CScript is the command-line executable for the scripting host that is used when you execute scripts from the command line. Although you can work with both of these hosts in much the same way, there are some features specific to each, which we discuss later in Chapter 4. For now, let’s focus on how the scripting hosts work.
Several file extensions are mapped for use with the scripting hosts. These file extensions are:
.js: Designates scripts written in JScript.vbs: Designates scripts written in VBScript.wsf: Designates a Windows script file.wsh: Designates a WSH properties fileA limitation of .js and .vbs files is that they can contain only JScript or VBScript statements, respectively, and you cannot mix and match. This is where .wsf files come into the picture. You can use .wsf files to create WSH jobs, or what I call batch scripts. These batch scripts can combine multiple types of scripts and can also include type libraries containing constants.
Batch scripts contain markup tags that identify elements within the batch, such as individual jobs and the scripting language being used. These markup tags are defined as XML (Extensible Markup Language) elements. XML is structured much like HTML and uses plain-text characters. You can use any text editor to create batch scripts and, because batch scripts contain XML, you can also use an XML editor.
Windows scripts can also use .wsh files. These files contain default settings for scripts, such as timeout values and script paths. Because of the introduction of .wsf files and direct in-script support for most script properties, .wsh files are rarely needed.
More on scripting engines
Scripting engines provide the core language functionality for Windows scripts and are packaged separately from the Windows Script Host itself. You can obtain scripting engines for JScript, VBScript, Perl, TCL, Python, and more. The official Microsoft scripting engines for VBScript and JScript are standard components on Windows and are the focus of this book.
With Windows scripting, many of the features available for scripting with Internet Explorer and the Web aren’t available. Functions needed for Web scripting simply aren’t needed for Windows scripting and vice versa. For example, in JScript, none of the window-related objects are available in WSH because, in Windows, you normally don’t need to access documents, forms, frames, applets, plug-ins, or any of those other browser-related features. The exception to this is if you create a script that starts a browser session; within the browser session, you can use the browser-related objects as much as you want.
Right now, you may be wondering what exactly is and isn’t supported by Windows scripts. In a nutshell, the scripting engines support core language and language runtime environments. The core language includes operators, statements, built-in objects, and built-in functions. Operators are used to perform arithmetic, comparisons, and more. Statements are used to make assignments, to conditionally execute code, and to control the flow within a script. For example, you can use for looping to execute a section of code for a specific count. These types of statements are all defined in the core language. Beyond this, the core language also defines the core functions and objects that perform common operations such as evaluating expressions, manipulating strings, and managing data.
The runtime environment adds objects to the core object model. These objects are used to work with the operating system and are available only with Windows Scripting. Table 1-2 provides a complete list of the available VBScript objects. The list is organized according to where the objects originate, either in the runtime environment or the core object model.
Table 1-2: VBScript Objects for Windows Scripting
Runtime ObjectsCore ObjectsDictionary object Class object Drive object Debug object Drives collection Dictionary object File object Err object Files collection FileSystemObject object FileSystemObject object Match object Folder object Matches collection Folders collection RegExp object TextStream object SubMatches collectionTable 1-3 provides a complete list of available JScript objects. Again, the list is organized according to where the objects originate.
Table 1-3: JScript Objects for Windows Scripting
Runtime ObjectsCore ObjectsArguments Object ActiveXObject Object Dictionary object Array object Drive object Boolean object Drives collection Date object File object Debug object Files collection Dictionary object FileSystemObject object Enumerator object Folder object Error object Folders collection FileSystemObject object TextStream object Function object Global object Math object Number object Object object RegExp object RegularExpression object String object VBArray objectWindows PowerShell Architecture
The name “PowerShell” explains the key architectural difference from the Windows Scripting Host. PowerShell began life as a command-line shell—like Windows CMD.EXE, and you can interact with it—so where VBScript or JScript programs are written in Notepad and run using the appropriate language inside the scripting host, the lines of a PowerShell script might be tested at a command prompt one by one and then gathered into a script.
As a shell, PowerShell can chain commands together using piping—that is, sending the output of one command into another using the | symbol. Often, development consists of running a command, checking its output, piping that output into something, checking that, and building up a long and complex line.
One of the important things that sets PowerShell apart from CMD.EXE is that where a command returns text to CMD, PowerShell’s commands return objects. The properties and methods of those objects can be used by commands further along a pipeline.
Compared with the WSH languages, PowerShell’s use of objects is both broader and deeper. Its use is deeper because .NET defines types such as text strings, and provides methods for working with them. PowerShell does not need to write a function for getting a substring from a bigger string—that’s inherited from .NET, as is PowerShell’s file handling, arithmetic, and so on (so PowerShell doesn’t need to implement the core functions found in the WSH languages). PowerShell’s use of objects is broader, because PowerShell has access to .NET objects, as well as COM ones and ready-made commands for getting to WMI and Active Directory objects.
WMI objects provide management, configuration, and performance information for many server applications and Windows components—indeed you could do a lot with just piping the output of PowerShell’s Get-WMIObject command into its Format-Table command.
PowerShell was designed to be highly extensible. Not only can your own scripts become part of the working environment, but also developers can write snap-ins that extend the environment with compiled code. These add to the set of commands available inside PowerShell—the term “command” in PowerShell covers all the different things that can be invoked from the prompt: external programs, scripts, functions loaded from scripts, and what PowerShell terms “CMDlets” from the snap-ins. PowerShell provides five snap-ins by default.
Table 1-4: PowerShell Snap-ins
Snap-inFunctionsCore Loads other snap-ins, provides access to command history, implements for loop, and where functionality Host Handles the console, manages transcripts Management Provides the commands to manage Windows components Security Handles credentials and secure strings Utility Provides the commands to format and output dataOther products that run on Windows can provide their own snap-ins—for example, Exchange2007, SQL Server 2008, and various members of the system center family provide their own snap-ins to allow PowerShell to be used as the scripting environment to manage them. At the time of this writing, Windows Server 2008 R2 has only just been announced: It will include an updated version of PowerShell, and more Windows components will have snap-ins to manage them.
The CMDLets snap-ins can also implement providers. The Security snap-in loads a provider for the Certificate store, so you can browse through it as if it were a file system. The Core snap-in has one for the registry, so you can treat branches of the registry like folders on your hard disk. Again, additional snap-ins can add to the list of providers.
Although PowerShell is a shell, it is possible to use the engine from another program without loading the “host”—the command Window that is wrapped around the engine. Increasingly it is expected that management tools for Microsoft products will be written as PowerShell snap-ins and then the GUI management tools will invoke CMDlets in these. This allows you to carry out a task in the GUI, discover the script that would carry it out, and use that as the basis for your own scripts.
PowerShell scripts have a .ps1 file extension, but to avoid the dangers of PowerShell automatically running a malicious script, the file type is not tied to the PowerShell executable. You can run PowerShell.exe with a command line that is the name of a script. Or you can invoke the script inside the shell. There is no equivalent to the choice between CScript and WScript.
Is there any need to learn anything other than PowerShell? That’s less of a point of argument between the contributors of this book than you might imagine. It’s going to become harder to be a properly rounded IT professional in a Microsoft environment without PowerShell, but the other languages will be with us for many years. Few organizations will see sense in re-writing a perfectly good VB or JScript script as a PowerShell one, and there are libraries and code samples that exist only in those languages. Sometimes it will make sense to translate them into PowerShell (which requires the ability to understand the script) and sometimes it will make sense to adapt an existing script in its existing language.
Summary
Now that you have a taste of what Windows scripting is all about, it’s time to go to the next level. Chapters 2, 3, and 4 provide essential scripting techniques for VBScript, JScript, and PowerShell, respectively. Carefully study these chapters before proceeding as they describe the core mechanics of scripting, covering variables, arrays, operators, conditional statements, control loops, procedures, and more. Once we have covered these core mechanics, we won’t waste your time rehashing how these features work with every future scripting example. Instead, we will trust that you’ve reviewed and understand the core mechanics and want to focus on the new materials we are discussing in a particular chapter. Even if you know some scripting basics, we recommend that you use these chapters to brush up on your VBScript, JScript, and PowerShell knowledge.
Chapter 2
VBScript Essentials
In This Chapter
Variable naming and typesUsing and sizing arraysWorking with conditional statementsUsing control loopsUnderstanding and using proceduresMicrosoft Visual Basic scripting edition (VBScript) has long been the favorite scripting language of Microsoft developers and soon it will be your favorite as well. VBScript is easy to learn and use, making the language a great choice, especially if you don’t have a programming background.
Working with Variables
Variables are a part of most scripting languages, and VBScript is no exception. A variable is simply a placeholder for a value you want to work with.
Variable naming
You can create a variable by assigning the variable a name, which you can refer to in your code later. Variable names, like other VBScript structures, follow standard naming conventions. These naming rules are as follows:
Names must begin with an alphabetic character.Names cannot contain periods.Names must be less than 256 characters in length.Variable names also have an additional property, which isn’t the case of other structures in VBScript. They are case-sensitive, meaning value1, Value1, and VALUE1 are all different variables. However, method, function, and object references in VBScript are not case-sensitive. For example, you can echo to the screen using any of the following commands:
wscript.echo "This is a test!"
Wscript.echo "This is a test!"
WScript.Echo "This is a test!"
But in reality, the correct capitalization for this reference is WScript.Echo.
Declaring variables
In VBScript, variables are declared either explicitly or implicitly. To declare a variable explicitly, use the keyword Dim to tell VBScript that you are creating a variable and then specify the variable name, such as:
Dim newString
You can then assign a value to the variable, such as:
newString = "I really love VBScript!"
You can also declare multiple variables at the same time. You do this by separating the variable names with commas:
Dim firstName, lastName, middleInitial
To declare a variable implicitly, use the variable name without first declaring it; you don’t need to use the Dim keyword. In this instance, VBScript creates the variable for you.
The problem with implicit variables is that any name is assumed to be valid, so you can mistakenly assign values to the wrong variable and you won’t know it. Consider the following example, in which you assign a value to theTotal and later assign a value to a variable called theTotals:
theTotal = sumA + sumB + sumC
'working with the variable
'now you need to increase the total
theTotals = theTotals + 1
Everything following a single quotation mark is interpreted as a comment. You can use comments anywhere in a line of code.
In this example, we meant to increase theTotal, but increased theTotals instead. To avoid situations like this, set Option Explicit, which requires that all variables be declared explicitly with the Dim keyword and also ensures the validity of your variables. This option should be placed at the beginning of your script, as shown in Listing 2-1.
Listing 2-1: Using Variables
vars.vbs
Option Explicit
'Setting variables
Dim sumA, sumB, sumC
Dim theTotal
sumA = 100
sumB = 10*10
sumC = 1000/10
'Get the total
theTotal = sumA + sumB + sumC
'write total to command-line using WScript.Echo
wScript.Echo "Total = ", theTotal
Output
300
Variable types
VBScript assigns all variables to the variant data type. Variants can hold numeric or string data and each is handled differently. The primary way in which VBScript determines if something is a number or a string is through the use of double quotation marks. In the previous code sample, sumA, sumB, and sumC are all handled as numbers. If you add double quotation marks to the values, they are treated as strings, as in the following example:
sumA = "100"
sumB = "10*10"
sumC = "1000/10"
The use of strings yields very different results when you add the values together, and as a result, the value of theTotal is:
10010*101000/10
The reason for this is that while numbers are summed, strings are concatenated so you get the literal sum of all characters in the string. To complicate things a bit more, VBScript also uses variable subtypes. Variable subtypes are summarized in Table 2-1. Subtypes enable you to put certain types of information into categories, which allows for better handling of dates, floating-point numbers, integers, and other types of variables. For example, if you are working with dates and you need to add two dates together, you wouldn’t want the result to be an integer. Instead, you’d want the dates to be handled as dates and the result of any operations to be dates, which is exactly what subtypes offer.
Table 2-1: Variable Subtypes in VBScript
SubtypeDescriptionBoolean A Boolean value that contains either True or False. Byte An integer byte value in the range 0 to 255. Currency A floating-point number in the range –922,337,203,685,477.5808 to 922,337,203,685,477.5807. Note the use of up to four decimal places. Date (Time) A number that represents a date between January 1, 100 to December 31, 9999. Double A double-precision, floating-point number in the range –1.79769313486232E308 to –4.94065645841247E–324 for negative values; 4.94065645841247E–324 to 1.79769313486232E308 for positive values. Empty An uninitialized variant. Value is 0 for numeric variables or an empty string ("") for string variables. Error An error number used with runtime errors. Integer An integer in the range –32,768 to 32,767. Long An integer in the range –2,147,483,648 to 2,147,483,647. Null A variant set to NULL that contains no valid data. Object An object reference. Single A single-precision, floating-point number in the range –3.402823E38 to –1.401298E–45 for negative values; 1.401298E–45 to 3.402823E38 for positive values. String A variable-length string.Generally, if you use whole numbers, such as 3 or 5, with a variable, VBScript creates the variable as an Integer. Variables with values that use decimal points, such as 3.125 or 5.7, are generally assigned as Doubles, double-precision floating-point values. Variables with values entered with a mixture of alphabetical and numeric characters, such as Yeah! and Q3, are created as Strings.
Converting variable types
VBScript can automatically convert between some variable types, and this eliminates most variable conflict. However, if you try to add a string variable to a numeric variable type, you will get an error. Because of this, do not try to perform numeric calculations with alphanumeric data.
That said, VBScript includes many different functions for converting data from one subtype to another. These functions are summarized in Table 2-2.
Table 2-2: Functions for Converting Variable Subtypes
FunctionDescription CBool(expression) Converts any valid expression to a Boolean value. Returns either True or False. CByte(expression) Converts any valid expression to a Byte value. CCur(expression) Converts any valid expression to a Currency value. CDate(date) Converts any valid date string to a Date value. Returns a date value that can be used when adding dates and times. CDbl(expression) Converts any valid expression to a Double value. CInt(expression) Converts any valid expression to an Integer value. CLng(expression) Converts any valid expression to a Long value. CSng(expression) Converts any valid expression to a Single value. CStr(expression) Converts any valid expression to a String value.Working with conversion functions is a lot easier than you may think. To convert a value, just pass the value to the conversion function, as follows:
stringA = "42"
stringB = "37"
intA = CInt(stringA) 'Set to integer value 42
intB = CInt(stringB) 'Set to integer value 37
The CBool(), CDate(), and CString() functions deserve a special note because they return output that is a bit different from what you might be used to. To learn more about these functions, take a look at Listing 2-2.
Listing 2-2: Using Conversion Functions
changetype.vbs
sumA = 30: sumB = 15 'Initialize variables
wscript.echo "sumA: " & TypeName(sumA)
wscript.echo "sumB: " & TypeName(sumB)
Test = CBool(sumA = sumB) 'Test contains false
sumB= sumB * 2 'Double value of sumB
Test = CBool(sumA = sumB) 'Test contains true
wscript.echo "Test: " & TypeName(Test)
dateStr = "December 10, 2005" 'Define a date as a string
wscript.echo "dateStr: " & TypeName(dateStr)
theDate = CDate(dateStr) 'Convert to Date data type
wscript.echo "theDate: " & TypeName(theDate)
timeStr = "8:25:10 AM" 'Define a time as a string
theTime = CDate(timeStr) 'Convert to Date data type
wscript.echo "timeStr: " & TypeName(timeStr)
wscript.echo "theTime: " & TypeName(theTime)
aDouble = 715.255 'Define a numeric value
aString = CStr(aDouble) 'Convert to a string
wscript.echo "aDouble: " & TypeName(aDouble)
wscript.echo "aString: " & TypeName(aString)
This code produces the following output:
sumA: Integer
sumB: Integer
Test: Boolean
dateStr: String
theDate: Date
timeStr: String
theTime: Date
aDouble: Double
aString: String
Working with Constants
Constants provide an easy way to use specific values without actually having to remember related value codes or strings. By using constants, you make it easier to maintain your code should the value of a constant ever change. You’ll also see constants referred to as literals. To help differentiate constants from variables, you should use a unique prefix or formatting.
Using built-in constants
In VBScript, constants are either intrinsic (built-in) or declared explicitly. VBScript has many built-in constants. Because built-in constants are already defined, you don’t need to explicitly declare them in your scripts. All VBScript constants begin with the prefix vb.
Table 2-3 shows the available color constants. Table 2-4 shows the available date and time constants. Many other constants are defined as well, and are referenced in the appropriate sections of this book.
Table 2-3: Color Constants
ConstantValueDescriptionvbBlack &h00 Black vbRed &hFF Red vbGreen &hFF00 Green vbYellow &hFFFF Yellow vbBlue &hFF0000 Blue vbMagenta &hFF00FF Magenta vbCyan &hFFFF00 Cyan vbWhite &hFFFFFF WhiteTable 2-4: Date and Time Constants
ConstantValueDescriptionvbSunday 1 Sunday vbMonday 2 Monday vbTuesday 3 Tuesday vbWednesday 4 Wednesday vbThursday 5 Thursday vbFriday 6 Friday vbSaturday 7 Saturday vbUseSystemDayOfWeek 0 First day of the week specified in system settings vbFirstJan1 1 Week in which January 1 occurs (default) vbFirstFourDays 2 First week that has at least four days in the new year vbFirstFullWeek 3 First full week of the yearDeclaring constants
You declare a constant explicitly using the keyword Const to tell VBScript that you are creating a constant, specify the constant name, and then assign a value to the constant, such as:
Const COMPANYID = "4876-54-32-87A"
Constant names don’t need to be in all caps. However, to give constants a unique formatting that differentiates them from variables, we decided to use all caps in the examples in this section.
Here, you are declaring the COMPANYID constant and setting a string value of 4876-54-32-87A. With string constants, the quotation marks are necessary to differentiate a string value from other types of values.
When you declare a numeric constant, you don’t need to use quotation marks. The following example declares a numeric constant:
Const PROJECTNUMBER = 789
Here, you are declaring the PROJECTNUMBER constant and setting a numeric value of 789.
You declare date and time constants by enclosing them in number signs (#), such as:
Const PROJECTSTARTDATE = #12-15-07#
Working with Arrays
