Read an Excerpt
VBScript Programmer's Reference
By Adrian Kingsley-Hughes Kathie Kingsley-Hughes Daniel Read
John Wiley & SonsISBN: 0-7645-5993-1
Chapter OneA Quick Introduction to Programming
A chapter covering the basics of VBScript is the best place to begin this book. Well, this is because of the type of language VBScript is and the kind of people we see turning to it. In this chapter we are going to try and give you 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, 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 nonprogramming 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 to write logon scripts and automate administration tasks.
You might be a Web designer who feels the need to branch out and increase their skill set, perhaps in order to do some ASP work.
You're interested in programming (possibly Visual Basic) and want to check out programming 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, please bear in mind that there's going to be a lot that we don't cover here, such as:
Advanced testing and rollout
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 what it hopefully will give you is the know-how you'll need in order to get the most out of the rest of the book.
Variables and Data Types
In this section, we're going to be moving quickly through some of the most basic concepts of programming. In particular:
Using built-in VBScript functions
The first thing you need to know about is variables. Quite simply, a variable is a place in the computer memory where your script holds a piece (or pieces) of information. Since computers work with data, we'll be using that word instead of information but the concept is the same. The data stored in a variable can be pretty much anything. It may be something simple, like a small number, like 4. It can be more complex, like a floating-point number such as 2.3. Or it could be 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, a temporary place to store data. Memory is temporary-things stored there are not stored permanently. For permanent storage you use the hard drive. Since memory is a temporary storage area, and since 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.
In order 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 of those chunks 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.
Note: It is not required that you have to declare all of the variables you use. VBScript by default allows you to use undeclared variables. However, we strongly recommend 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.
By declaring variables you also give them a name in the process. Here's an example of a variable declaration in VBScript.
By doing this, what you in factdoing is giving the computer an instruction to reserve some memory space for you and give that chunk the name YourName. From now on, the computer (or, more accurately, the VBScript script engine) keeps track of that memory for you, and whenever you use the variable name YourName, it will know what you're talking about.
Variables are essential to programming. Without them you have no way to hold all the data that your script will be handling. Every input into the script, output from the script, and process within the script uses variables. They are the computer's equivalent of the sticky notes that we leave all over the place with little bits of information on them. All the notes are important (otherwise why write them?) but they are also temporary. Some might become permanent (so you take a phone number and write it down in your address book or PDA), while others are thrown away after use (say, after reminding you do something). This is how it works with variables too. Some hold data that you might later want to keep, while others are just used for general housekeeping and are disposed of as soon as they're used.
In VBScript, whenever you have a piece of information that you need to work with, you declare a variable using the exact same syntax that we showed you a moment ago. At some point in your script, you're going to need to do something with the memory space you've allocated yourself (otherwise, what would be the point of declaring it?) And what you do with a variable is place a value in it. This is called "initializing" the variable. Sometimes you initialize a variable with a default value. Other times, you might ask the user for some information, and initialize the variable with whatever the user enters. Alternatively, you might open a database and use a previously stored value to initialize the variable.
Note: When we say "database" we don't necessarily mean an actual database but any store or data-it might be an Internet browser cookie or a text file that we get the data from.
Initializing the variable gives you a starting point. After it has been initialized, you can begin making use of the variable in your script.
Here's a very simple VBScript example.
Dim YourName ' Above we dimensioned the variable YourName = InputBox("Hello! What is your name?") ' Above we ask for the user's name and initialize the variable MsgBox "Hello " & YourName & "! Pleased to meet you." ' Above we display a greeting containing the user's name
Quite rightly, you're now probably wondering what all this code means. Last time we showed you one line and now it's grown to six.
All of the examples in this chapter are designed so that you can run them using the Windows Script Host (WSH). The WSH is a scripting host that allows you to run VBScript programs within Windows. WSH will allow you to try out these example programs for yourself. You may already have WSH installed. To find out, type the above example script into a text editor, save the file as TEST.VBS (it must have the .VBS extension, and not a .TXT), and double-click the file in Windows Explorer. If the script runs, then you're all set. If Windows does not recognize the file, then you'll need to download and install WSH from msdn.microsoft.com/scripting.
You already know what the first line of code does. It declares a variable for use called YourName.
The second line in our code is a comment. In VBScript, any text that is preceded by the single quote character (') is treated as a comment. What this means is that the VBScript script engine will completely ignore the text. So, if the VBScript engine just ignores any text typed after the single quote character, why bother typing it in at all? It doesn't contribute to the execution of the script, right? This is absolutely correct, but don't forget one of the most important principles of programming: It is not just computers that may have to read script. It is equally important to write a script with human readers in mind as it is to write with the computer in mind.
Of course, none of this means that we are for one moment forgetting that when we are writing our scripts, we must write them with the computer (or, more specifically, the script engine) in mind. If we don't type the code correctly (that is, if we don't use the proper syntax), the script engine won't be able to execute the script. However, humans are also involved in programming. Once you've written some useful scripts, you're probably going to have to go back to make some changes to a script you wrote six months or a year ago. If you didn't write that code with human readers in mind as well as a computer reader, it could be pretty difficult to figure out what you were thinking and how you decided to solve the problems at the time you wrote the script. Things can get worse. What happens when you or one of your coworkers has to make some changes to a script you wrote many months ago? If you did not write that script to be both readable and maintainable, others that useyour code will encounter difficulties deciphering thecode-no matter how well written the actual computer part of the code is.
Adding comments to your code is just one part of making sure code is clear and readable. There are many other things that you can do:
Choosing clear, meaningful variable names
Indenting code for clarity
Making effective use of white space
Organizing the code in a logical manner
All of these aid human-readability and we'll be covering all of these later, but clear, concise comments are by far the most important. However, too much of a good thing is never good and the same is true for comments. Overburdening code with comments doesn't help. Remember that if you are scripting for the Web that all the code, including the comments, are downloaded to the browser and so unnecessary comments may adversely affect download times.
We'll discuss some good commenting principles later in this chapter, but for now just be aware of the fact that the comment we have in line 2 of our script is not really a good comment for everyday use. This is because, to any semi-experienced programmer, it is all too obvious that what we are doing is declaring the YourName variable on the line above. However, throughout this book you will often see the code commented in a similar way. This is because the point of our code is to instruct the reader in how a particular aspect of VBScript programming works. The best way for us to do that is to add comments to the code directly. It removes ambiguity and keeps the code and comments together.
Also worth noting is that comments don't have to be on a separate line. Comments can also follow the code, like so :
Dim YourName ' initialize the variable YourName = InputBox("Hello! What is your name?") ' ask for the user's name MsgBox "Hello" & YourName & "!Pleased to meet you."' display a greeting
This works in theory but it isn't as clear as keeping the comments on separate lines in the script.
OK, back to the script. Take a look at line 3.
YourName = InputBox("Hello! What is your name?")
Here we are doing two things at once. First, we're initializing the variable. We could do it directly, like this:
YourName = "Fred"
However, the drawback with this is that we are making the arbitrary decision that everyone is called Fred, which is ideal for some applications but not for others. If we wanted to assign a fixed value to a variable, such as a tax rate, this would be fine.
Dim TaxRate TaxRate = 17.5
However, we want to do something that gives the user a choice, which is why we employ the use of a function, called InputBox. We'll be looking at this function and all the others in later chapters, but for now all you need to know is that InputBox is used to display a message in a dialog box, and it waits for the user to input text or click a button. The InputBox generated is displayed in Figure 1-1.
The clever bit is what happens to the text that the user types into the input box displayed-it is stored in the variable YourName.
Line is another comment. Line 5 is more code. Now that we've initialized this variable, we're going to do something useful with it. MsgBox is another built-in VBScript function that you will probably use quite a lot during the course of your VBScript programming. Using the MsgBox function is a good way to introduce the programming concept of passing function parameters, also known as arguments. Some functions don't require you to pass parameters to them while others do. This is because some functions (take the Date function as an example-this returns the current date based on the system time) do not need any additional information from you in order to do their job. The MsgBox function, on the other hand, displays a piece of information to the user in the form of a dialog box, like the one shown in Figure 1-2.
You have to pass MsgBox a parameter because on its own it doesn't have anything useful to display (in fact, it will just bring up a blank pop-up box). The MsgBox function actually has several parameters, but for now we're just going to look at one. All of the other parameters are optional parameters.
Take another look at line 5 and you'll probably notice the ampersand (&). The ampersand is a VBScript operator, and is used to concatenate (join) pieces of text together. To concatenate simply means to "string together." This text can take the form of either a literal or a variable. A literal is the opposite of a variable. A variable is so named because it is exactly that-a variable-and can change throughout the lifetime of the script (a script's lifetime is the time from when it starts executing, to the time it stops executing). Unlike a variable, a literal cannot change during the lifetime of the script. Here is line 5 of the script again.
MsgBox "Hello " & YourName & "! Pleased to meet you."
An operator is a symbol or a word that you use within your code that is usually used to change or test a value.
Excerpted from VBScript Programmer's Reference by Adrian Kingsley-Hughes Kathie Kingsley-Hughes Daniel Read Excerpted by permission.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.