Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


July 1999

Scripting 101, Part 2


RSS
Subscribe to Windows IT Pro | See More Task Automation Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Download the Code Here

Using On Error Resume Next to help trap errors is important. Suppose I comment out (i.e., add Rem to the beginning of) the line that declares variable intReturnCode at the beginning of demo.vbs:

Rem Dim arrStrings, intReturnCode

If I execute this modified script, the script will run to completion, but it might not produce the desired result. The script won't display the standard WSH Script Execution Error message on the console; instead, the script will produce Screen 2's custom error dialog box, which states that a script variable is undefined. The If-Then-End If statement at callout B in Listing 1 acts as a rudimentary error-handling routine that echos the contents of the VBScript Err object's Number and Description properties. After you click OK to acknowledge the error dialog box, the script continues because the On Error Resume Next directive tells the script to proceed despite the error. (If I commented out the On Error Resume Next directive and ran the script again, Screen 1's WSH Script Execution Error dialog box would display. More important, the script would abort as soon as I clicked OK in Screen 1's dialog box; I'd have no control over the remainder of the script. The only benefit of not using On Error Resume Next is that the error information in the WSH Script Execution Error dialog box can be more descriptive than the information in the Err object's Description property. Screen 1 not only includes the name of the undefined variable, it also provides the specific line number for the error. In Screen 2, the error description simply states that the script tried to use an undefined variable.)

Why does an error occur? In demo.vbs, I initialize intReturnCode to 0 in line 19 of the script, a few lines before callout A. But because I specified the Option Explicit directive at the start of the script and commented out intReturnCode's declaration statement, an error occurs when the script tries to execute the line that initializes the undeclared intReturnCode to 0. I can eliminate this error and other potential variable declaration errors by removing the Option Explicit statement. However, a better way to fix the problem is to define the undeclared variable (in this case, remove the Rem from the declaration statement):

Dim arrStrings, intReturnCode

Unlike Option Explicit, which affects the entire script, On Error Resume Next applies to only the portion of the script (e.g., the script's body, a function, a subroutine) that defines it. On Error Resume Next's narrow scope lets you control precisely when and where it's in effect. (VBScript doesn't support Visual Basic's—VB's—On Error Goto Label construct.) When you use the Option Explicit and On Error Resume Next directives correctly, they can make VBScript routines more robust and user-friendly and play an important role in debugging scripts.

VBScript variables. Earlier, I said declaring variables in VBScript is optional—and it is. However, engaging in the exercise of defining your script's variables can be well worth your time and effort for several reasons, such as debugging and script maintenance. Declaring your script's variables also requires you to consider the environment and objects with which your script interacts, which can result in better-designed scripts that do what you intend them to do.

A VBScript variable is simply a named memory location that contains some value. The value might be a number, a string, or some other data type that the language supports. The variable name is the mechanism through which you assign a value to a variable. Declaring VBScript variables identifies the names that you'll use to refer to the data your script manipulates.

You use the Dim statement to declare VBScript variables. In demo.vbs, the variable declarations follow the script directives at the beginning of the script. VBScript supports one primary data type: variant. You can think of variants as general-purpose variables that aren't bound to a specific type. When you declare a VBScript variable using Dim, you don't supply additional type information as you do in VB. Instead, VBScript determines a variable's type at runtime, based on the variable's contents and the usage context. VBScript supports many different data subtypes and corresponding data conversion functions that let you morph variants to your heart's content. For more information about VBScript variables, download the free VBScript HTML Help file (vbsdoc.exe) at http://msdn.microsoft.com/ scripting/vbscript/ download/vbsdoc.exe.

Variable initialization. Variable initialization is nothing more than assigning a known value to a variable before you use the variable. In demo.vbs, I initialize several variables before using the variables in the script's body. You can initialize a variable to one value, such as a number or a string, or to a more complex value constructed from multiple elements.

For example, in the variable initialization section of demo.vbs, the script assigns to strLogFile the concatenation (from VBScript's & operator) of three substrings. The first substring ("c:\") and third substring (".log") are straightforward. The second or middle substring retrieves the value of WScript's ScriptName property (in this case, "demo.vbs") and splits the string into two strings at the dot (.). In this example, I append the subscript (0) to the end of the function call to force the Split function to return only the first element ("demo") of the array of elements that Split ordinarily returns. The end result is a log file name that is identical to the script name without the extension.

Constant definitions. Constants are named values that don't change throughout the execution of a script. VBScript supports two types of constants: literal and intrinsic. Literal constants are constants that you define for the purpose of making your script more intelligible. Let's say that you write a script that uses the value of Pi (¼). Rather than hard-coding the numeric value each time the script needs it, you might define the following literal constant:

Const Pi = 3.1415926535897932384626433832795

When you need to reference the value of Pi in your script, you simply use the constant's name (i.e., Pi). In this example, referring to the name is much easier than (and significantly reduces potential typing errors from) coding the numeric value each time the script needs to use Pi. Furthermore, if you need to change the value of a constant at some later date, you need to update the constant's value in only one place in the script: in the line where you defined the constant. You can assign only scalar values to VBScript literal constants. The language doesn't support constants constructed from other constants or expressions.

Intrinsic constants are constants that are built into the VBScript language to make the language easier to use and make your scripts easier to read and maintain. Some of my favorite intrinsic constants include the escape sequence constants such as vbNewLine and vbTab that represent ANSI character codes, which you'll find sprinkled throughout demo.vbs. The VBScript Language Reference and the Scripting Run-Time Reference in the VBScript Help file provide a complete list of constants.

VBScript doesn't let you use constants that other objects, such as the scripting runtime's FileSystemObject and ADSI, define. However, Microsoft plans to include this capability in the next release of WSH. In the interim, if you want to use constants that other objects define, simply duplicate the constant definition in your script. In the constant definitions section of demo.vbs, I define the local constant OpenFileForReading to mimic the behavior of FileSystemObject's OpenFileForReading constant.

Demo.vbs End
Before I go, I should tell you what the demo script does. Demo.vbs simply runs NT's ipconfig.exe utility, writes the commands' output to a file, opens and displays the file, deletes the file, and records the success or failure of each major action along the way to a log file. Then, the demo.vbs script opens the resulting log file, displays the file, deletes the file, and exits. Next month, to continue my scripting trek, I'll examine some of the more important elements generally found in the body of a script: I/O and object handling.

End of Article

   Previous  1  [2]  Next  


Reader Comments
My employer mandates that Perl is our scripting language. I noted that all of the articles in this series assume that VB is the scripting language, but this is not acceptable here. Is it possible to use Perl to create WSH scripts?

Arnold Schoenberg December 13, 1999


Learn HTML first

Anonymous User January 10, 2005


gooooooooood

Anonymous User February 22, 2005 (Article Rating: )


You must be a registered user or online subscriber to comment on this article. Please log on before posting a comment. Are you a new visitor? Register now




Top Viewed ArticlesView all articles
Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

2009 Windows IT Pro Editors' Best and Community Choice Awards

Picking a favorite product from an impressive crowd of competitive offerings is never an easy task, and such was the case with our Editors' Best and Community Choice awards this year. ...

WinInfo Short Takes: Week of November 23, 2009

An often irreverent look at some of the week's other news, including some post-PDC some soul searching, a Google Chrome OS announcement and a Microsoft response, Windows 7 off to a supposedly strong start, the Jonas Brothers and Xbox 360, and so much more ...


Related Articles Scripting 101, Part 4

Scripting 101, Part 3

Scripting 101

Task Automation Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Related Events Deep Dive into Windows Server 2008 R2 presented by John Savill

Check out our list of Free Email Newsletters!

Task Automation eBooks Spam Fighting and Email Security for the 21st Century

A Guide to Windows Certification and Public Keys

Keeping Your Business Safe from Attack: Patch Management

Related Task Automation Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement