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

Declaring and initializing variables
In last month's column, I discussed the structure of a script. I divide scripts into three sections: declarations and initializations, the body of the script, and function and subroutine definitions. This month, I continue my journey into the fundamentals of scripting by examining the declaration and initialization section in detail. Before we start, you need to know some VBScript basics to ease your transition to Windows Scripting Host (WSH).

VBScript Basics
As with any other programming or scripting language, VBScript has some general ground rules that apply to every script. At first glance, these rules might not appear to be significant, but knowing these language tidbits can often shave a few minutes off a frustrating debugging exercise.

The first ground rule is that VBScript isn't case-sensitive. For example, declaring a variable as strTempFile and later referencing it as STRtEMPfILE is perfectly legal. Likewise, VBScript statements, function names, and subroutine names are case-insensitive. Despite this flexibility, I encourage you to pick a case variation that suits your needs and stick with it.

Although VBScript is case-insensitive, some situations (e.g., comparing two string values) require you to be case-conscious. You also need to be case- conscious when you use Active Directory Service Interfaces (ADSI) namespace identifiers (e.g., LDAP to specify Lightweight Directory Access Protocol, WinNT to specify Windows NT, NDS to specify NetWare 4.x, NWCOMPAT to specify NetWare 3.x). You must key ADSI namespace identifiers according to the ADSI specification, or a runtime error will occur when your script attempts to bind to an ADSI namespace. (For more information about ADSI namespace usage, read the Active Directory Programmer's Guide available at http://msdn.microsoft.com/ developer/windows2000.)

The second VBScript rule is that you can use either an apostrophe (´) or a Rem statement to include comments in a script. I use both styles in Listing 1's demo.vbs script, page 160. You can insert comments on a separate line or at the end of a line of code, but you can't insert comments at the end of a code line that contains a line-continuation marker (_).

A third rule is that VBScript doesn't care about extra white space. Adding extra spaces or blank lines can often improve the code's readability. VBScript ignores the blank lines and the extra spaces between the variable name and the assignment operator (=).

The fourth rule is that although VBScript doesn't impose a maximum line length, breaking long lines into multiple short lines can improve the readability of a script. In VBScript, you can use the line-continuation marker to let a statement or line of code span multiple lines. I often use the line- continuation marker when I initialize dynamic arrays (e.g., at callout A in Listing 1) or to pass a long string to WScript's Echo method (WScript.Echo), which I demonstrate several times in the body of the demo.vbs script. When you use the line-continuation marker, you need to include one space immediately before the underscore, or you will encounter an error with some statement types.

On the flip side of rule 4 is the fifth VBScript ground rule, which lets one line of code contain multiple statements. In VBScript, you can use a colon (:) to separate multiple statements within a line of code. In the code line

  Dim strText: strText = "WSH ROCKS!" : WScript.Echo strText  

statement 1 is Dim strText, statement 2 is strText = "WSH ROCKS!", and statement 3 is WScript.Echo strText. Although VBScript supports this capability, I generally don't use it.

The sixth VBScript rule is that you must terminate each line of VBScript code with a new-line character. Pressing Enter automatically inserts the new- line character. VBScript doesn't use the visible line terminator (;) that JScript and Perl use.

The seventh and final ground rule in this month's lesson governs VBScript identifiers (e.g., variables, constants, function names, subroutine names). Identifiers can't exceed 255 characters in length and must begin with an uppercase or lowercase letter of the alphabet.

Bob's Declaration and Initialization Section
The primary elements that make up my declaration and initialization section are script directives, variable declarations, constant definitions, and variable initialization. All these elements (with the possible exception of initialization) are optional. However, using these language features can help you produce scripts that are easier to debug and maintain.

VBScript directives. VBScript includes two directives or statements that significantly affect the runtime behavior of scripts. The two directives are the Option Explicit statement and the On Error Resume Next statement.

The Option Explicit statement requires that you declare (i.e., define) all script variables via a VBScript Dim statement before you use the variables in an expression. When you use Option Explicit, the declaration requirement applies throughout the entire script, including variables in the main body of the script and variables in user-defined functions and subroutines. You must include the Option Explicit statement before any other statements in your script. Therefore, you always find Option Explicit at the top of scripts that use it. The benefit of using Option Explicit is that an error occurs whenever the VBScript interpreter encounters an undefined variable during script execution. Using Option Explicit helps you isolate typographical mistakes and variables with incorrect scopes (a scope defines the visibility of a variable to other parts of the script such as functions and subroutines).

The On Error Resume Next statement controls how a script notifies you when a script encounters a runtime error. When a script runtime error occurs and the script doesn't use the On Error Resume Next statement, WSH displays a dialog box containing the execution error information and aborts the script. Screen 1 shows an example WSH Script Execution Error dialog box. Including an On Error Resume Next statement in a script effectively tells VBScript to continue execution despite a runtime error: VBScript's built-in Err object is set with the corresponding error information, and the script continues. The On Error Resume Next statement lets you trap errors and respond to them programmatically. You can choose to display a friendly, descriptive message or write the error information to a log file. Screen 2 shows an example customized error dialog box.

   Previous  [1]  2  Next 


Top Viewed ArticlesView all articles
WinInfo Short Takes: Week of November 9, 2009

An often irreverent look at some of the week's other news, including some more Windows 7 sales momentum, some Sophos stupidity, Microsoft's cloud computing self-loathing, more whining from the browser makers, Zoho's "Fake Office," and much, much more ...

Windows 7 Sets Sales Record

Microsoft CEO Steve Ballmer described Windows 7's first ten days of sales as "fantastic" while in Japan yesterday. ...

Microsoft Completes Layoffs

Microsoft on Wednesday announced that it was laying off 800 more workers, bringing its previously-announced layoff plan to a close. ...


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

Will Your Next Generation Server System Meet Your Infrastructure Optimization Needs?

Continuous Data Protection and Recovery for Microsoft Exchange

Related Events WinConnections and Microsoft® Exchange Connections

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