Contents

Acknowledgments

Introduction

Chapter 1: A Quick Introduction to Programming

Variables and Data Types

Flow Control

Operators and Operator Precedence

Organizing and Reusing Code

Top-Down versus Event-Driven

Coding Guidelines

Summary

Chapter 2: What VBScript Is — and Isn’t!

Windows Script

Version Information

VBScript Is a Subset of VB

VBScript Is a Scripting Language

VBScript Is Interpreted at Runtime

Advantages of Using VBScript

Is VBScript Right for You?

How VBScript Fits in with the Visual Basic Family

What Can You Do with VBScript?

Tool of the Trade — Tools for VBScript

Summary

Chapter 3: Data Types

Scripting Languages as Loosely Typed

Why Data Types Are Important

The Variant: VBScript’s Only Data Type

Arrays as Complex Data Types

Summary

Chapter 4: Variables and Procedures

Option Explicit

Naming Variables

Procedures and Functions

Variable Scope, Declaration, and Lifetime

Design Strategies for Scripts and Procedures

ByRef and ByVal

Literals and Named Constants

Summary

Chapter 5: Control of Flow

Branching Constructs

Loop Constructs

Summary

Chapter 6: Error Handling and Debugging

Types of Errors

Error Visibility and Context

Handling Errors

Generating Custom Errors

Debugging

Summary

Chapter 7: The Scripting Runtime Objects

What Are Runtime Objects?

Object Basics

The Dictionary Object

The FileSystemObject Library

Summary

Chapter 8: Classes in VBScript (Writing Your Own COM Objects)

Objects, Classes, and Components

The Class Statement

Defining Properties

Defining Methods

Class Events

Class-Level Constants

Building and Using a Sample VBScript Class

Summary

Chapter 9: Regular Expressions

Introduction to Regular Expressions

The RegExp Object

The Matches Collection

A Few Examples

Summary

Chapter 10: Client-Side Web Scripting

Tools of the Trade

The Evolution of Scripting

Different Scripting Languages

Responding to Browser Events

The Document Object Model in Action

Summary

Chapter 11: Windows Sidebars and Gadgets

Gadget Basics

Building a Gadget

Auto-Refresh a Gadget

Packaging the Gadget

Summary

Chapter 12: Task Scheduler Scripting

Working with Task Scheduler

Task Scheduler 2.0 Scripting Objects

Sample Task Scheduler Script

Summary

Chapter 13: PowerShell

Requirements

Features

Why a New Scripting Language?

Getting Started

Working with Scripts in PowerShell

Creating and Calling Your First PowerShell Cmdlet Script

The Connection Between VBScript and PowerShell?

Summary

Chapter 14: Super-Charged Client-Side Scripting

Requirements and Browser Security

Scriptlets — Ancestors of Behaviors

Event Management

Scriptlets Are Deprecated in IE5

HTML Components (HTCs)

Summary

Chapter 15: Windows Script Host

Tools of the Trade

What Is WSH?

Types of Script Files

Running Scripts with the Windows Script Host

Using .WSH Files to Launch Scripts

Windows Script Host Intrinsic Objects

Summary

Chapter 16: Windows Script Components

What Are Windows Script Components?

What Tools Do You Need?

The Script Component Runtime

Script Component Files and Wizard

Exposing Properties, Methods, and Events

Registration Information

Creating the Script Component Type Libraries

How to Reference Other Components

Script Components for ASP

Compile-Time Error Checking

Using VBScript Classes in Script Components

Summary

Chapter 17: Script Encoding

Limitations of Script Encoding

Encoded Scripts — Dos and Don’ts

Encoding with the Microsoft Script Encoder

Decoding the Script

Other Methods of Script Obfuscation

Summary

Chapter 18: Remote Scripting

How Remote Scripting Works

Using VBScript for Remote Scripting

Summary

Chapter 19: HTML Applications

The Advantage of an HTML Application

How to Create a Basic HTA

Turning an HTML File into an HTML Application

The HTA:APPLICATION Element

Accessing Other HTA:APPLICATION Attributes

HTAs and Security

Using Nested Frames

HTA Deployment Models

Package Model

Hybrid Model

What Isn’t Supported with HTAs?

Summary

Chapter 20: Server-Side Web Scripting

Understanding the Anatomy of the HTTP Protocol

Introducing Active Server Pages

Using the Active Server Pages Object Model

Using Active Server Pages Effectively

Summary

Chapter 21: Adding VBScript to Your VB and .NET Applications

Why Add Scripting to Your Application?

Macro and Scripting Concepts

Adding the Script Control to a VB 6 or .NET Application

Script Control Reference

Error Handling with the Script Control

Debugging

Using Encoded Scripts

Sample .NET Project

Sample Visual Basic 6 Project

Summary

Appendix A: VBScript Functions and Keywords

Appendix B: Variable Naming Convention

Appendix C: Coding Conventions

Appendix D: Visual Basic Constants Supported in VBScript

Appendix E: VBScript Error Codes and the Err Object

Appendix F: The Scripting Runtime Library Object Reference

Appendix G: The Windows Script Host Object Model

Appendix H: Regular Expressions

Appendix I: The Variant Subtypes

Appendix J: ActiveX Data Objects

Index

VBScript Programmer’s Reference, Third Edition

Published by

Wiley Publishing, Inc.

10475 Crosspoint Boulevard

Indianapolis, IN 46256

www.wiley.com

Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-16808-0

Library of Congress Cataloging-in-Publication Data

Kingsley-Hughes, Adrian.

VBScript programmer’s reference / Adrian Kingsley-Hughes, Kathie Kingsley-Hughes, Daniel Read.

p. cm.

Includes index.

ISBN 978-0-470-16808-0 (paper/website)

1. VBScript (Computer program language) 2. HTML (Document markup language) 3. World Wide Web. I. Kingsley-Hughes, Kathie. II. Read, Daniel, 1969– III. Title. IV. Title: VB Script programmer’s reference.

QA76.73.V27K56 2007

005.2' 762—dc22

2007028895

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 Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, 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 Website 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 Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites 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 (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress 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. 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.

To my kids—you guys are great!

—Adrian

To my parents, for their loving support and enduring patience.

And to my kids, for being just so cool!

—Kathie

About the Authors

Adrian Kingsley-Hughes has made his living as a technology writer for over a decade, with many books and articles to his name. He can also be found teaching classes on the Web, where he has successfully taught technology skills to thousands of learners, with his own special brand of knowledge, experience, wit, and poor spelling. He is also editor of the ZDNet blog Hardware 2.0 (http://blogs.zdnet.com/hardware).

Kathie Kingsley-Hughes has worked in IT training for many years. In addition to writing, she now works as a courseware developer and e-trainer, specializing in Internet technologies. She also runs a web development company in the United Kingdom.

Daniel Read is a software developer living and working in Atlanta, GA, USA. He currently works for Connecture Inc., an Atlanta-based software consulting firm specializing in the insurance industry. Daniel also publishes and writes essays for developers at DeveloperDotStar.com, a web-based magazine for software professionals.

Credits

Acquisitions Editor

Katie Mohr

Development Editor

Maureen Spears

Technical Editor

Andrew Moore

Copy Editor

Mildred Sanchez

Editorial Manager

Mary Beth Wakefield

Production Manager

Tim Tate

Vice President and Executive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Joseph B. Wikert

Project Coordinator, Cover

Adrienne Martinez

Proofreader

Ian Golder

Indexer

Johnna VanHoose Dinse

Anniversary Logo Design

Richard Pacifico

Acknowledgments

Writing a book is hard work, and writing a third edition is even harder! The process involves a lot more people than just those listed on the cover (although thanks must got to Kathie and Dan for their hard work). My sincerest thanks goes out to everyone who made this book possible, from the initial idea of revamping this title for a second time to getting it onto the shelves.

—Adrian

Many thanks to family, friends, and colleagues, who have been very supportive during the writing of this book. A big thank you to all the editors, tech reviewers, and production staff who worked so hard on this edition.

—Kathie

I thank my fellow authors, Adrian and Kathie, and also the fine editorial staff at Wiley.

—Daniel

Introduction

Imagine having the ability to write code quickly and easily in a text editor without having to worry about complex development environments.

Imagine not having the hassles of compiling code or distributing complex set-up programs.

Imagine being able to deploy your code in a wide variety of ways.

Imagine learning one language that allows you to code for server-side Internet, client-side Internet, and desktop.

Stop imagining. VBScript gives you all this and much more.

VBScript is an absolutely superb language to be able to “speak” in. It’s quick and easy to learn, powerful, flexible, and cheap. This makes it a winning language for both experienced programmers and those starting out in their programming careers. If you are an experienced programmer, you can enjoy writing code free from complex development environments and the need for compiling. On the other hand, if you are a beginner, you can get started programming, needing nothing more than a little knowledge and a text editor.

Knowledge and experience in VBScript can open many technology doors, too. Having a good grounding in VBScript can lead you into areas such as Internet development, network administration, server-side coding, and even other programming languages (Visual Basic being the most popular route to take because the languages are so similar in syntax). With VBScript, you can also create applications that look and feel like programs written using complex programming languages, such as C++. Also worth bearing in mind is that support for scripting is now embedded into every installation of the newer Windows operating systems — a dormant power that you can tap into with VBScript know-how. By writing some simple script in a text editor, you can do a variety of tasks, such as copy and move files, create folders and files, modify the Windows registry, and lots more. One easy-to-use scripting language can do it all.

We believe that knowing how to program in VBScript is a skill that many people will find both useful and rewarding, whether they are involved in the IT industry, a SOHO PC user, a student, or simply a home user. Knowing and using VBScript can save you time and, more importantly, money.

Whom This Book Is For

This is the one-stop book for anyone who is interested in learning VBScript. How you use it depends on your previous programming/scripting knowledge and experience:

If you are a complete beginner who has heard about VBScript and have come this far, that’s great. You’ve come to the best possible place. As a beginner, you have a fascinating journey ahead of you. We suggest that you go through this book from cover to cover to get the best from it.

If you already have IT and programming experience and want to learn VBScript (perhaps for Active Server Pages (ASP) or Windows Scripting Host (WSH), then you, too, have come to the right place. Your background in programming means that you will already be familiar with most of the terms and techniques that we cover here. For you, the task of learning another language is made simpler by this. If you know what you plan to be using VBScript for (say ASP or WSH), then you can read with this in mind and skip certain chapters for speed.

Network administrators are likely to find this book not only useful, but also an enormous timesaver because they can use VBScript to write powerful logon scripts or automate boring, repetitive, time-consuming, and error-prone tasks using WSH.

You’re already using VBScript and just want to fill in some of the blanks or bought this new edition just to keep up-to-date. You will no doubt find new information and you might want to read certain chapters more than others (such as the Windows Vista–specific chapters of the revamped appendixes).

What This Book Covers

As you’d expect, a book on VBScript covers VBScript. To be precise, this book covers VBScript right up to the latest version (version 5.7). However, VBScript is a tool that can be used in a variety of different ways and by a variety of different applications. Therefore, along with covering VBScript in detail, this book also covers technologies that are linked to and associated with VBScript. These include technologies such as Windows Script Host (WSH). Likewise, if you come from a Visual Basic background, then most of what is covered in the first third of the book (variables, data types, procedures, flow control, and so on) will be familiar to you. This book also shows you how to get deep into the Windows operating system and make changes with just a few lines of code.

How This Book Is Structured

Take a quick look at the table of contents of this edition and you’ll see that it’s broken up into three broad sections:

The book begins with chapters that are core VBScript — basically how VBScript works as a language.

The book looks at how to make use of VBScript within other technologies (such as WSH or ASP). These chapters look at more advanced examples of VBScript code in action.

The book has a detailed and comprehensive reference section in the form of a series of appendixes. You can use this reference section as a stand-alone section, or to gain greater insight into how the VBScript from earlier chapters works.

How you decide to progress through the book really depends on your current skill level with regards to VBScript or other programming languages and what you want to do. It’s your book — use it the way that best suits you!

If you’re not sure about the best way to approach this book, we suggest that you read it from beginning to end, so that you benefit fully. Don’t worry too much about actually remembering everything you read — that’s not the point. The book is a reference, which means you can refer back to it again and again. Make notes in the book as you go. This will help you remember better and aid in your finding key parts you’ve read before.

What You Need to Use This Book

VBScript is possibly a low-cost solution to many of your scripting/programming needs. The good news is that you (and your end users) use a Microsoft Windows operating system, so you already have everything you need to be able to make full use of this book (or you can go online to download it).

All the code writing can be done using the Windows Notepad application that you already have installed. We will make a few suggestions about other tools you can use that may make life easier for you, but a text editor is all you really need.

The Microsoft Scripting web site contains documentation relating to VBScript that is available for download. You may like to download these, too, to augment your reading here.

If you are not using Windows Vista or XP, you might want to download the latest VBScript engine — point your browser at www.microsoft.com/scripting.

Conventions

To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.

Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

We highlight important words when we introduce them.

We show keyboard strokes like this: Ctrl+A.

We show filenames, URLs, and code within the text like so: persistence.properties

We present code in two different ways:

In code examples, we highlight new and important code with a gray background.

The gray highlighting is not used for code that's less important in the present context, or has been shown before.

Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany this book. All the source code used in this book is available at www.wrox.com. Once at the site, simply locate the book’s title by using the Search box. You can then choose what you want to download.

Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-16808-0.

Errata

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration; at the same time, you will be helping us provide even higher quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book’s detail page, click the Book Errata link. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list including links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

p2p.wrox.com

For authors and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to email you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At p2p.wrox.com, you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.

2. Read the terms of use and click Agree.

3. Complete the required information to join as well as any optional information you wish to provide and click Submit.

4. You will receive an email with information describing how to verify your account and complete the joining process.

You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum emailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

Chapter 1

A Quick Introduction to Programming

A chapter covering the basics of VBScript is the best place to begin this book. This is because of the type of language VBScript is and the kind of users the authors see turning to it. In this chapter, you get a crash course in programming basics. You might not need this chapter because you’ve come to VBScript with programming skills from another language (Visual Basic, Visual Basic .NET, C, C++, Delphi, C#) and are already both familiar with and comfortable using programming terminology. In that case, feel free to skip this chapter and move on to the next one. However, if you come from a non-programming background, then this chapter will give you the firm foundation you need to begin using VBScript confidently.

If you’re still reading, chances are you fall into one of three distinct categories:

You’re a Network/Systems administrator who probably wants to use VBScript and the Windows Script Host or PowerShell to write logon scripts or to automate administration tasks.

You might be a web designer who feels the need to branch out and increase your skill set, perhaps in order to do some ASP work.

You’re interested in programming (possibly Visual Basic or Visual Basic .NET) and want to check it out before getting too deeply involved.

Programming is a massive subject. Over the years countless volumes have been written about it, both in print and on the Internet. In this chapter, in a single paragraph, we might end up introducing several unfamiliar concepts. We’ll be moving pretty fast, but if you read along carefully, trying out your hand at the examples along the way, you’ll be just fine.

Also, do bear in mind that there will be a lot that we don’t cover here, such as:

Architecture

System design

Database design

Documenting code

Advanced testing, debugging, and beta testing

Rollout and support

Think of this chapter as a brief introduction to the important building blocks of programming. It certainly won’t make you an expert programmer overnight, but it will hopefully give you the know-how you’ll need to get the most out of the rest of the book.

Variables and Data Types

In this section, you’ll quickly move through some of the most basic concepts of programming, in particular:

Using variables

Using comments

Using built-in VBScript functions

Understanding syntax issues

Using Variables

Quite simply, a variable is a place in the computer memory where your script holds a piece (or pieces) of information, or data. The data stored in a variable can be pretty much anything. It may be something simple, like a small number, like 4, something more complex, like a floating-point number such as 2.3, or a much bigger number like 981.12932134. Or it might not be a number at all and could be a word or a combination of letters and numbers. In fact, a variable can store pretty much anything you want it to store.

Behind the scenes, the variable is a reserved section of the computer’s memory for storing data. Memory is temporary — things stored there are not stored permanently like they are when you use the hard drive. Because memory is a temporary storage area, and variables are stored in the computer’s memory, they are therefore also temporary. Your script will use variables to store data temporarily that the script needs to keep track of for later use. If your script needs to store that data permanently, it would store it in a file or database on the computer’s hard disk.

To make it easier for the computer to keep track of the millions of bits of data that are stored in memory at any given moment, the memory is broken up into chunks. Each chunk is exactly the same size, and is given a unique address. Don’t worry about what the memory addresses are or how you use them because you won’t need to know any of that to use VBScript, but it is useful to know that a variable is a reserved set of one or more chunks. Also, different types of variables take up different amounts of memory.

In your VBScript program, a variable usually begins its lifecycle by being declared (or dimensioned) before use.

It is not required that you declare all of the variables you use. By default, VBScript allows you to use undeclared variables. However, it’s strongly recommended that you get into the good habit of declaring all of the variables you use in your scripts. Declaring variables before use makes code easier to read and to debug later. Just do it!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!