Visual Basic Scripting Edition & Windows Script Host Essentials PDF
Visual Basic Scripting Edition & Windows Script Host Essentials PDF
® ®
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Contents
Introduction
Course Materials ......................................................................................................2
Prerequisites.............................................................................................................3
Course Outline .........................................................................................................4
Expectations.............................................................................................................6
Microsoft Certified Professional Program ...............................................................7
Facilities...................................................................................................................9
Module 1: Overview of Windows Scripting Technologies
Overview..................................................................................................................1
Introducing WSH.....................................................................................................2
Running Scripts........................................................................................................9
Working with Scripts .............................................................................................17
Comparing VBScript and Visual Basic .................................................................24
Lab 1: Configuring and Using WSH......................................................................26
Review ...................................................................................................................32
Module 2: Working with Objects
Overview..................................................................................................................1
Object Terminology .................................................................................................2
Creating and Using Objects ...................................................................................11
Understanding Object Models ...............................................................................16
Demonstration: Using an Object Browser .............................................................23
Common Object Models ........................................................................................29
Lab 2: Working with Objects.................................................................................39
Review ...................................................................................................................46
Module 3: Script Logic
Overview..................................................................................................................1
Fundamental VBScript Rules ..................................................................................2
Variables, Constants, and Data Types .....................................................................4
Operators................................................................................................................22
Conditions and Loops ............................................................................................28
Procedures..............................................................................................................41
Script Layout..........................................................................................................48
Lab 3: Working with VBScript..............................................................................56
Review ...................................................................................................................63
Module 4: Error Handling and Debugging
Overview..................................................................................................................1
Error Handling .........................................................................................................2
Debugging..............................................................................................................10
Lab 4: Debugging and Error Handling ..................................................................15
Review ...................................................................................................................22
iv Microsoft® Visual Basic® Scripting Edition and Microsoft Windows® Script Host Essentials
Description
This three-day instructor-led course provides students with the knowledge and
experience to develop their own administrative scripts with Microsoft® Visual
Basic® Scripting Edition (VBScript). The course focuses on writing scripts for
commonly encountered administrative tasks. The course also expands upon
these concepts so that they embrace more general programming issues.
Audience
This course is intended for Microsoft Windows® 2000 systems administrators
who want to learn how to develop administrative scripts for their enterprise
networks.
In addition, anyone who wants an introduction to the VBScript programming
language will benefit from this course.
Student Prerequisites
This course requires that students meet the following prerequisites. The
students must have:
Practical experience using and administering Windows 2000.
Practical experience using and administering Active Directory™ directory
service.
Practical experience using and administering system security.
Practical experience using and administering services.
Practical experience using systems management information.
Awareness of the potential uses of logon scripts.
In addition, it is desirable that students have had some exposure to writing batch
files.
Course Objectives
After completing this course, students will be able to:
Describe Windows Script Host (WSH) and associated scripting
technologies.
Use objects in code written in Visual Basic Scripting Edition.
Master the essentials of the VBScript language.
Master debugging and error handling with VBScript.
Use VBScript to interact with Active Directory Services Interface (ADSI).
Develop logon, logoff, startup, and shutdown scripts.
Develop scripts that perform common administrative tasks.
Identify ways to use VBScript in other scenarios.
vi Microsoft® Visual Basic® Scripting Edition and Microsoft Windows® Script Host Essentials
Course Timing
The following schedule is an estimate of the course timing. Your timing may
vary.
Day 1
Start End Module
9:00 9:30 Introduction
9:30 10:15 Module 1: Overview of Windows Scripting Technologies
10:15 11:00 Lab 1: Configuring and Using WSH
11:00 11:15 Break
11:15 12:45 Module 2: Working with Objects
12:45 1:45 Lunch
1:45 2:30 Lab 2: Working with Objects
2:30 3:00 Module 3: Script Logic
3:00 3:15 Break
3:15 3:45 Module 3: Script Logic (continued)
3:45 4:15 Lab 3: Working with VBScript
Day 2
Start End Module
9:00 9:30 Day 1 review
9:30 10:00 Module 4: Error Handling and Debugging
10:00 10:30 Lab 4: Debugging and Error Handling
10:30 10:45 Break
10:45 11:30 Module 5: Understanding ADSI
11:30 11:45 Lab 5.1: ADO Search
11:45 12:30 Module 5: Understanding ADSI (continued)
12:30 1:30 Lunch
1:30 2:15 Lab 5.2: Scripting Administrative Tasks Using ADSI
2:15 2:45 Module 6: Creating Logon Scripts
2:45 3:00 Lab 6.1: Creating Logon Scripts
3:00 3:15 Break
3:15 3:45 Lab 6.1: Creating Logon Scripts (continued)
3:45 4:00 Module 6: Creating Logon Scripts (continued)
Microsoft® Visual Basic® Scripting Edition and Microsoft Windows® Script Host Essentials vii
Day 3
Start End Module
9:00 9:30 Day 2 review
9:30 10:15 Lab 6.2: Assigning Logon Scripts
10:15 10:45 Module 7: Administrative Scripts
10:45 11:00 Break
11:00 11:30 Lab 7.1: Administrative Scripts
11:30 12:00 Module 7: Administrative Scripts (continued)
12:00 1:00 Lunch
1:00 1:30 Lab 7.2: Working with the FileSystemObject
1:30 2:00 Module 8: Beyond the Basics
2:00 2:15 Break
2:15 2:45 Module 8: Beyond the Basics (continued)
viii Microsoft® Visual Basic® Scripting Edition and Microsoft Windows® Script Host Essentials
Document Conventions
The following conventions are used in course materials to distinguish elements
of the text.
Convention Use
Contents
Introduction 1
Course Materials 2
Prerequisites 3
Course Outline 4
Expectations 6
Microsoft Certified Professional Program 7
Facilities 9
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Introduction iii
Instructor Notes
Presentation: This module provides students with an overview of the course content,
30 Minutes materials, and logistics for Course 2433A, Microsoft Visual Basic Scripting
Edition and Microsoft Windows Script Host Essentials.
Required Materials
To teach this course, you need the following materials:
Delivery Guide
Trainer Materials compact disc
Microsoft PowerPoint® file 2433A_00.ppt
Preparation Tasks
To prepare for this module, you must complete the Course Preparation
Checklist that is included with the trainer course materials.
iv Introduction
Module Strategy
Use the following strategy to present this module:
Course 2433A, Microsoft Visual Basic Scripting Edition and Microsoft
Windows Script Host Essentials
Display the slide with the course number and title.
Introduction
Introduce yourself, and provide a brief overview of your background to
establish your credibility as a Microsoft® Visual Basic® Scripting Edition
and Microsoft Windows® Script Host instructor.
Ask students to introduce themselves and provide their backgrounds,
product experience, and expectations for the course.
Course Materials
Explain the purpose of all materials used in this course.
Prerequisites
Provide the students with the list of prerequisites that they should meet
before taking this course. This is an opportunity for you to identify students
who may not have the appropriate background or experience to attend this
course.
Course Outline
Provide an overview of each module and of what students will learn.
Explain how this course will meet students’ expectations by relating the
information covered in individual modules to their expectations.
Expectations
Use this section to set and manage the students’ expectations. Emphasize
what the course provides. Also, emphasize what it does not provide.
Facilities
Explain the facility information for the training site.
Introduction 1
Introduction
Topic Objective
To introduce yourself,
establish credibility, meet
students, and set student
Name
expectations for the course. Company Affiliation
Lead-in
Good morning. Welcome to Title/Function
Microsoft Visual Basic
Scripting Edition and
Job Responsibility
Microsoft Windows Script Scripting and Programming Experience
Host Essentials.
Microsoft Windows 2000 Experience
My name is...
Expectations for the Course
Introduce yourself.
Course Materials
Topic Objective
To identify and describe the
course materials.
Lead-in Name Card
We have provided Student Workbook
everything you need for this
course. You will find the Student Materials Compact Disc
following materials at your
desk... Course Evaluation
Describe the contents of the The following materials are included with your kit:
student workbook and the
Student Materials compact Name card. Write your name on both sides of the name card.
disc. Student workbook. The student workbook contains the material covered in
class, in addition to the hands-on lab exercises.
Have students write their
names on both sides of the Student Materials compact disc. The Student Materials compact disc
name card. contains the Web page that provides you with links to resources pertaining
to this course, including additional readings, review and lab answers, lab
Tell students where they files, multimedia presentations, and course-related Web sites.
can send comments with
feedback on the course.
Note To open the Web page, insert the Student Materials compact disc into
Delivery Tip the CD-ROM drive, and then in the root directory of the compact disc,
Demonstrate how to open double-click Autorun.exe or Default.htm.
the Web page provided on
the Student Materials
compact disc. On the Course evaluation. To provide feedback on the instructor, course, and
Trainer Materials compact software product, send e-mail to [email protected]. Be sure to type
disc, double-click Course 2433A in the subject line. Your comments will help us improve
Autorun.exe or future courses.
Default.htm in the
StudentCD folder.
To provide additional comments or inquire about the Microsoft Certified
Professional program, send e-mail to [email protected].
Introduction 3
Prerequisites
Topic Objective
To present and describe the
prerequisites for this course.
Lead-in Course 1560, Updating Support Skills from Microsoft
The following prerequisite Windows NT 4.0 to Windows 2000, or equivalent
knowledge is needed for this knowledge
course.
Experience with a Batch Language Is an Advantage
No Programming Experience Is Assumed
Course Outline
Topic Objective
To provide an overview of
Module 1: Overview of Windows Scripting Technologies
each module and what
students will learn. Module 2: Working with Objects
Lead-in
In this course, we will Module 3: Script Logic
cover...
Module 4: Error Handling and Debugging
Module 5: Understanding ADSI
Module 6: Creating Logon Scripts
Module 7: Administrative Scripts
Module 8: Beyond the Basics
Expectations
Topic Objective
To set the students
expectations.
Lead-in What This Course Provides:
This course is intended to A detailed introduction to Windows Script Technologies
give you a good introduction
to script. A detailed introduction to writing code in VBScript
Examples of working scripts
Reference materials
What This Course Does Not Provide:
A description of all script functionality
http://www.microsoft.com/trainingandservices/
For More Information See the “Certification” section of the Web page provided
on the compact disc or the Microsoft Training and Certification Web site at
http://www.microsoft.com/trainingandservices/
You can also send e-mail to [email protected] if you have specific
certification questions.
8 Introduction
Facilities
Topic Objective
To inform students of class Class Hours
logistics and rules for the
training site.
Lead-in Building Hours Phones
Before we start, let’s go over
the class logistics.
Parking Messages
Meals Recycling
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 1: Overview of Windows Scripting Technologies iii
Instructor Notes
Presentation: This module provides students with the knowledge required to understand the
45 Minutes Microsoft® Windows® Script Host (WSH) environment and associated
technologies.
Lab:
45 Minutes After completing this module, students will be able to:
Describe the various technologies associated with running Windows Scripts.
Run scripts.
Work with scripts.
Describe the major differences between Microsoft Visual Basic® and
Visual Basic Scripting Edition.
Required Materials
To teach this module, you need the following materials:
Microsoft PowerPoint® file 2433A_01.ppt
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
iv Module 1: Overview of Windows Scripting Technologies
Module Strategy
Use the following strategy to present this module:
Introducing WSH
This section introduces the WSH environment and features.
Explain that WSH is not a single application, but is actually made up of
different components. Make sure that the students have a conceptual
understanding of the following terms:
• Hosts
• Script engines
• Object models
In the Types of Script Files section, go through the table provided with the
whole class to ensure that they understand the significance of the different
file extensions.
Running Scripts
The most important information in this section is the distinction between the
two different hosts, WScript and CScript. Stress that WScript is the default
host, but also explain that the students can change this.
The distinction between the two natively supported languages, Visual Basic
Scripting Edition and Microsoft JScript®, is also important.
Working with Scripts
Use this section to make sure that the students understand that there are
many tools available to them for writing scripts. Also, stress the fact that the
students will find the reference documentation invaluable as they start
writing scripts. Note that the students will install and review the
documentation as part of Lab 1 at the end of the module.
Do not spend too much time on the debugging topic. It is only included as
an overview for the sake of completeness. Module 4, “Error Handling and
Debugging,” deals with debugging in much more depth.
Comparing VBScript and Visual Basic
Finish the module with this single slide topic. Note that this is not a
definitive list of the differences between Visual Basic Scripting Edition and
Visual Basic, but merely illustrates that there are differences between the
two languages. Although the topic concentrates on some differences, you
should stress to the students that the languages are in fact very similar.
Emphasize to the students that if they are already familiar with the
Visual Basic language, then writing VBScript will be easy.
Module 1: Overview of Windows Scripting Technologies v
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Training and
Certification courseware.
Lab Setup
There are no lab setup requirements that affect replication or customization.
Module 1: Overview of Windows Scripting Technologies 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Introducing WSH
Lead-in Running Scripts
In this module, you will learn
about Windows Script Host Working with Scripts
and how to work with script
files. Comparing VBScript and Visual Basic
Introducing WSH
Topic Objective
To introduce the WSH
environment and the
features of WSH. The WSH Environment
Lead-in Features of WSH
By using WSH, you can run
scripts. Types of Script Files
Hosts
Hosts are the programs that run your scripts. Before WSH was developed,
Internet Information Services (IIS) and Microsoft Internet Explorer were the
only hosts available from Microsoft. As a result, scripting was restricted to the
Web. However, with the addition of CScript.exe and WScript.exe, you can now
run scripts outside of the Web environment. These hosts accept scripts and
determine which script engine you need to parse, interpret, and execute those
scripts.
Script Engines
The WSH environment natively supports two scripting languages: Visual Basic
Scripting Edition and JScript.
After the scripting host determines the language used in your scripts, it loads
the appropriate script engine and passes your script to it for execution. WSH
includes two different script engines, one for VBScript and one for JScript, to
run scripts that you write in these languages.
4 Module 1: Overview of Windows Scripting Technologies
Object Models
Script programming usually makes extensive use of objects. Objects represent
packaged functionality that you can reuse in your scripts. They provide a
concept known as black-box reuse. You use objects in your scripts to perform
many tasks. The advantage of using objects is that they perform complex tasks
without requiring you to understand how to implement the code they contain.
Related objects are defined in structures called object models. The object
models are defined by type libraries contained in dynamic link libraries (DLL)
or ActiveX Control (OCX) files.
When you install WSH, you install the hosts, two native script engines and two
object models, the Windows Script Host, and the Script Run-time object
models.
Note For more information about objects and specific object models, see
Module 2, “Working With Objects,” in Course 2433A, Microsoft Visual Basic
Scripting Edition and Microsoft Windows Script Host Essentials.
Extensibility
This WSH environment is extensible. You can install additional script engines
to use new script languages. You can also install new type libraries to gain
access to additional object models.
Module 1: Overview of Windows Scripting Technologies 5
Features of WSH
Topic Objective
To describe the features of
Windows Script Host.
Lead-in Small Memory Footprint
WSH is a low-memory script Language-Independent
host that is ideal for
administrative scripting. You can extend it to other script engines
Script Reuse
Command-Line Reference
Language-Independent
Although WSH natively supports the Visual Basic Scripting Edition and JScript
languages, you can extend the environment so that it can run scripts written in
other languages, such as PerlScript.
Script Reuse
By using WSH, you can save your scripts as operating system files. The content
of your script files is plain text. Therefore, you can write and save your script
files by using a simple text editor such as Notepad. After you save the script
files, you can run your scripts many times; you do not need to rewrite code
every time you want to run a certain set of actions. This is a useful feature if
you have scripts that must be run on a regular basis.
6 Module 1: Overview of Windows Scripting Technologies
Command-Line Reference
Prior to WSH, the only native script language that the Windows operating
system supported was the command language supported though Cmd.exe.
Administrators often construct batch files (.bat) that contain multiple
commands. These commands are still supported and are an important part of the
administrator’s toolset.
In addition, specially written command utilities, such as those provided in the
Windows 2000 Resource Kit, can be the most efficient way to get a task done.
You will explore some of these command-line utilities and learn how they can
be integrated with Visual Basic Scripting Edition throughout this course.
A full command-line reference is provided in Windows 2000 Help.
Module 1: Overview of Windows Scripting Technologies 7
Script Files
The .vbs and .vbe files are script files written in the Visual Basic Scripting
Edition language. A .vbe file is an encoded version of the script.
Similarly, the .js and .jse files are scripts written in JScript. A .jse file is an
encoded version of the script.
Note For more information about .vbe files, see Module 6, “Creating Logon
Scripts,” in Course 2433A, Microsoft Visual Basic Scripting Edition and
Microsoft Windows Script Host Essentials.
8 Module 1: Overview of Windows Scripting Technologies
This creates a .wsh file with the same name as the script file and in the same
folder as the script file.
Note The .wsh file works in a similar way that shortcuts (.lnk) or .pif files
work in Windows. It is a pointer to the file that you want to execute. It also
configures the environment settings that the script will inherit.
In the above example, the Path setting identifies the script file that this .wsh file
executes. The Timeout setting sets a maximum script execution time of 20
seconds. The DisplayLogo setting is set to 0, which means that a run-time logo
will not be displayed.
Note For more information about the features available to a .wsf file, see
Module 8, “Beyond the Basics,” in Course 2433A, Microsoft Visual Basic
Scripting Edition and Microsoft Windows Script Host Essentials.
Running Scripts
Topic Objective
To describe the two script
hosts available to WSH.
Lead-in Running Scripts with Wscript.exe
Let’s look at the two hosts Running Scripts with Cscript.exe
available to WSH.
Script Language Engines
This example stops the WSH from displaying its logo when it runs the
Myscript.vbs script.
Script name
This is the name of the script file, complete with extension and any
necessary path information. For example:
Example CScript C:\Scripts\Qbackup.vbs
This example runs the script file Qbackup.vbs in the C:\Scripts folder.
Module 1: Overview of Windows Scripting Technologies 13
Be aware of the difference between using a single forward slash and a double
forward slash to pass parameters at the command line. The former indicates
data that is to be passed into the script, and the latter is used as a setting for the
CScript environment.
CScript Parameters
Each parameter is optional. If you simply type CScript at the command
prompt, the CScript syntax and the valid host parameters are displayed.
CScript.exe supports the host parameters listed in the following table.
Parameter Description
Note The host parameters described in the previous table are not case
sensitive.
14 Module 1: Overview of Windows Scripting Technologies
This changes the default host to CScript.exe for the duration of the users logon
session.
If you were to add the //S option to this command, the setting is saved for the
current user and is the default every time the user logs on to the computer in the
future.
You could then use the //S option to save these setting for the currently logged on user
Note These settings are stored in the registry at the following location:
HKEY_CURRENT_USER\Software\Microsoft\Windows Scripting
Host\Settings
Module 1: Overview of Windows Scripting Technologies 15
VBScript
If you are new to programming, then VBScript will be easier to learn. VBScript
will also be easier to learn if you have a background in programming using
Visual Basic or Visual Basic for Applications.
16 Module 1: Overview of Windows Scripting Technologies
Microsoft JScript
If you have a background in C, Microsoft Visual C++®, or Java, then Microsoft
JScript is more appropriate. You will find that it has more familiar
programming constructs than VBScript.
With each update of the scripting engines, Microsoft is bringing the feature sets
of the languages closer together. Also, with the addition of XML support in
WSH version 2.0, you can use the language that is best suited to a particular
task, even within the same script. You can develop scripts that have a mix of
languages contained within them. One section can be written in VBScript, and
another section can be written in JScript, all within the same script file.
Note There are a few areas in which one scripting languages is more powerful
than the other. For example, JScript has very powerful error handling routines,
whereas Visual Basic Scripting Edition has excellent run-time expression
evaluation. Detailed comparison of the two languages is outside the scope of
this course.
For more information about the differences between VBScript and JScript, see
http://msdn.microsoft.com/scripting/default.htm
Module 1: Overview of Windows Scripting Technologies 17
Writing Scripts
Topic Objective
To explain what
components are required to WSH 2.0
write a script.
Lead-in
Part of Windows 2000 and Windows ME
Before you can start Download for Windows NT 4.0, Windows 95, and
creating scripts you must Windows 98
have a development tool to
write them with, and a host Development Tools
to run them on.
Notepad
Third-party IDEs
Visual InterDev or Visual Basic for Applications
Reference Documentation
WSH 2.0
WSH 2.0 ships with the following versions of Windows:
Windows Millenium Edition (Me)
Windows 2000 Professional
Windows 2000 Server
Windows 2000 Advanced Server
Windows 2000 Datacenter Server
WSH version 1.0 is integrated into Windows 98. Both Windows 95 and
Windows NT version 4.0 were released before WSH, so they must be upgraded
to support WSH 2.0. You can download an upgrade for Windows 95 and
Windows 98 and a service pack for Windows NT 4.0. WSH 2.0 includes:
Visual Basic Scripting Edition and JScript version 5.1
Windows Script Runtime version 5.1
Note Updates to the script engines also ship with Internet Explorer updates.
For example, version 5.5 of the script engines ships with version 5.5 of
Internet Explorer. Check the documentation of future updates of
Internet Explorer to find which script engine version they contain.
Module 1: Overview of Windows Scripting Technologies 19
Development Tools
Currently, WSH is shipped without a dedicated development tool for scripting.
However, you can obtain tools that enable you to develop scripts on your
Windows platform.
The most basic development tool is Notepad.exe. Using Notepad as your
scripting development tool has the following advantages:
It is installed on all Windows machines by default.
It supports cut and paste and other text-editing operations.
It has low memory and processor requirements.
Using Notepad does not impose any specific limitations on the code that you
develop. However, this tool provides no specific scripting functionality, such as
object browsing or integrated debugging.
There are other development tools available from third parties that are far more
powerful than Notepad. There are also the Integrated Development
Environments (IDEs) of Microsoft Visual InterDev® and Visual Basic for
Applications. These programs offer features that include the Object Browser
and mature, integrated debugging tools. However, these tools are not designed
exclusively for Visual Basic Scripting Edition. As a result, there are
compatibility and programmatic issues that you need to understand before you
can use these tools to develop scripts.
Reference Documentation
It is a good idea to install the Visual Basic Scripting Edition and Windows
Script Host online reference documentation. These provide an invaluable guide
to the objects, methods, and properties that are available in VBScript and WSH,
as well as many examples. The VBScript documentation also provides a
reference to the VBScript language syntax.
You can install the WSH documentation by downloading and running
Wshdoc.exe from:
http://msdn.microsoft.com/scripting/windowshost/wshdoc.exe
You can install the VBScript documentation and samples by downloading and
running Vbsdoc.exe from:
http://msdn.microsoft.com/scripting/VBScript/download/vbsdoc.exe
20 Module 1: Overview of Windows Scripting Technologies
Debugging Scripts
Topic Objective
To introduce common bugs
and demonstrate how the
Microsoft Script Debugger Script Errors
can help track these bugs.
Syntax errors
Lead-in
As you write scripts, it is Run-time errors
inevitable that errors will
occur. These errors fall into Logic errors
three basic categories.
Microsoft Script Debugger
Installing Microsoft Script Debugger
Features of Microsoft Script Debugger
Script Errors
Errors in your script can be categorized into three groups:
Syntax errors.
This type of error results when you have not followed all of the rules of the
language. For example, omitting a quotation mark where one is required
will generate a syntax error. Syntax errors are picked up as the script is
compiled and executed. For this reason they are sometimes called
compilation errors.
Compilation is the process of turning the code that you write into a set of
instructions that the processor can execute. Syntax errors will prevent your
code from running. You will receive a message box that indicates the type
of syntax error that has occurred.
Run-time errors.
A run-time error occurs when your code, although syntactically correct,
attempts to perform an action that is not possible at the time it is attempted.
For example, a run-time error occurs if your script attempts to open a file
that does not exist or attempts to save a file to the floppy drive when no disk
is present. Run-time errors cause your script to stop unexpectedly. You will
receive a message box that indicates the type of action that was attempted
but was not possible.
Module 1: Overview of Windows Scripting Technologies 21
Logic errors.
A logic error occurs when a script runs without syntax or run-time errors,
but the results are unexpected or unintended. For example, a script might
prompt the user for a password. The script is supposed to prevent the user
from proceeding without a valid password, but it allows the user to process
without a password. This could be due to a logic error in the script.
Logic errors are typically the most difficult ones to fix, because they are the
most difficult ones to identify. Logic errors usually results in bugs in your
script.
Microsoft Script Debugger can be used to run your code line-by-line to see
why the script does not run the script the way it was intended. This is the
most efficient approach to finding and fixing logic errors.
Note The script debugger documentation is written with the focus on Internet
scripts rather than WSH. While this can be confusing for an administrator who
has no Internet Explorer script experience, the majority of the information it
provides can be applied to WSH scripting.
To see how to use the features of Microsoft Script Debugger, see Module 4,
“Error Handling and Debugging,” in Course 2433A, Microsoft Visual Basic
Scripting Edition and Microsoft Windows Script Host Essentials.
22 Module 1: Overview of Windows Scripting Technologies
Troubleshooting
Topic Objective
To provide basic
troubleshooting tips. WScript.Echo Method
Lead-in Generates a message box in WScript
When you are working with
scripts, you must be aware Outputs to the command line in CScript
of some basic
troubleshooting information. The Debugger Launches Without a Loaded Script
From the command-prompt, check which line caused the
failure
Log off and log back on to reset the debugger
Visual Studio Installation
Overrides Microsoft Script Debugger
WScript.Echo Method
The following statement behaves differently in WScript and CScript:
Example WScript.Echo "This is a message"
With WScript.exe, this method results in a message box that interrupts the
execution of the script until the user clicks OK.
With CScript.exe, this method outputs the text directly to the command line and
then continues executing the script. No user interaction is required.
Caution Modifying the registry can result in your machine being unable to
start. Always ensure you have a system backup before changing any registry
values.
24 Module 1: Overview of Windows Scripting Technologies
Syntax Differences
Unlike Visual Basic, Visual Basic Scripting Edition does not require that the
main body of the script be enclosed in a Sub () or Function () procedure.
VBScript has only one data type, called a Variant, which is used to contain
many different kinds of data. For example, it contains strings, integers, and so
on. You cannot declare an explicit data type in VBScript.
There is no support in VBScript for the Debug.Print statement used in Visual
Basic. The WSH equivalent is WScript.Echo.
Module 1: Overview of Windows Scripting Technologies 25
One limitation of VBScript is its lack of native support for referencing type
library information. This is most apparent with constants. If you wish to use a
constant name to reference a value, you must explicitly declare it at the start of
the script.
Note With the XML support in WSH 2.0, you can overcome this limitation.
For more information, see Module 8, “Beyond the Basics,” in Course 2433A,
Microsoft Visual Basic Scripting Edition and Microsoft Windows Script Host
Essentials.
This is not a definitive list of the differences between the languages. It simply
illustrates that there are some important differences that will affect the ability to
reuse code examples from one language in the code to another language.
26 Module 1: Overview of Windows Scripting Technologies
Objectives
After completing this lab, you will be able to:
Run scripts.
Configure a WSH file for your scripts.
Manage the WSH environment on a computer.
Edit scripts by using an IDE.
Prerequisites
Before working on this lab, you must have:
An understanding of the Windows 2000 graphical user interface (GUI).
The ability to work with Windows Explorer.
Scenario
You are the administrator of a corporate network. You want to run scripts
written in Visual Basic Scripting Edition by using WSH technologies. You
must control and configure the script host that you will use to run your scripts.
In addition, you want to install the documentation for WSH and VBScript.
Finally, you want to review and edit scripts by using an IDE.
Exercise 1
Configuring WSH
In this exercise, you will examine and configure the various settings for the
WSH environment.
Exercise 2
Installing the WSH and VBScript documentation
In this exercise, you will install and review the WSH and Visual Basic Scripting
Edition documentation.
Exercise 3
Using an IDE to Edit Script Files
In this exercise, you will use the PrimalSCRIPT IDE.
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. Introducing WSH
Lead-in Running Scripts
The review questions cover
some of the key concepts Working with Scripts
taught in the module.
Comparing VBScript and Visual Basic
Contents
Overview 1
Object Terminology 2
Creating and Using Objects 11
Understanding Object Models 16
Demonstration: Using an Object Browser 23
Common Object Models 29
Lab 2: Working with Objects 39
Review 46
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 2: Working with Objects iii
Instructor Notes
Presentation: This module provides students with the knowledge and practical experience of
90 Minutes using objects in scripts.
Lab: After completing this module, students will be able to:
45 Minutes
Understand how scripts use objects.
Understand object terminology.
Use an object browser.
Understand how scripts interact with the Component Object Model (COM).
Explain the use of various object models.
Required Materials
To teach this module, you need the following materials:
Microsoft® PowerPoint® file 2433A_02.ppt
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
iv Module 2: Working with Objects
Module Strategy
Use the following strategy to present this module:
Object Terminology
This section introduces the students to the terms that they will encounter
when programming with objects. It is essential that they understand all of
the terms in this section, because much of the rest of the course uses objects.
Spend as much time as necessary to make sure that the students understand
the relationship between objects and their methods and properties. Also,
ensure that the students fully understand the distinction between a class and
an object. Use the analogies given in this section to help explain the
terminology to students who have not encountered these terms before.
Creating and Using Objects
This section reinforces the previous section by giving some examples of
how objects can be used.
Make use of the examples in the text and on the slides to expand the
students’ understanding of how objects are created and used.
Understanding Object Models
Explain that COM is a binary specification developed by Microsoft that
makes the reuse of objects possible. Then, introduce the object browser and
the object models described in this section.
It is very important that the students understand the purpose of the two
object models described in this section. They will use both the Microsoft
Windows® Script Host (WSH) and the scripting object models in the lab.
They will also work with these object models on an everyday basis at work.
Common Object Models
Use this section to introduce some of the other object models that the
students will find useful at work. You will not have time to go into any
detail about these object models themselves. Also, note that some of the
object models are covered in more detail later in the course. Use this section
as an introduction to these object models.
Module 2: Working with Objects v
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Training and
Certification courseware.
Lab Setup
There are no lab setup requirements that affect replication or customization.
Module 2: Working with Objects 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Object Terminology
Lead-in Creating and Using Objects
In this module, you will learn
about objects and how they Understanding Object Models
are used in scripts.
Common Object Models
Object Terminology
Topic Objective
To introduce object
terminology.
Lead-in Understanding Object Terminology
Using objects in your scripts Methods and Properties
will afford you many
advantages. Understanding Instantiation Terminology
Objects
Objects are packaged pieces of functionality. Objects contain code that you can
use in your scripts. However, the manner in which you access the functionality
contained in an object is called black-box reuse. When you use the functionality
provided by an object, you never need to see the code that it contains.
Compiled Objects
The most common types of objects that you will use in your Microsoft® Visual
Basic® Scripting Edition (VBScrpt) files are compiled objects. With these types
of objects, you will never need to see the code that they contain. The code that
provides the functionality is compiled into a binary file, which is usually a
dynamic link library (DLL) or a Microsoft ActiveX® Control file (with the file
extension .ocx). All that you need to do is create script in VBScript that
communicates with the object to reuse the prepackaged functionality that it
provides.
In addition to containing code that provides reusable functionality, objects also
contain data. You can manipulate this data in a manner similar to reusing the
packaged functionality. You do not need to know how the object implements its
data. You only need to know how to communicate with the object to manipulate
the data values. Again, this is all part of the black-box reuse concept.
You will communicate with the functionality provided by an object by using its
methods. You will manipulate the data that an object contains by working with
its properties. Methods and properties are described in the following section.
4 Module 2: Working with Objects
Note Each object that you work with has a well-defined list of methods and
properties associated with it. For example, one object might contain a Color
property and a Paint method, while another object might contain a Name
property and a Play method. The methods and properties that each individual
object contains are designed by the developer of that object.
Module 2: Working with Objects 5
Methods
Objects expose their functionality as methods. To use the functionality provided
by a particular method, you need to know how to call it. You do not need to
know how the method works internally. The term invoke is often used to
describe the process of calling a method.
When you invoke a method in your script, the compiled method code runs in its
entirety at the point in your code where you call it. It is important to understand
the benefits that this affords you as a script developer. The method might
contain thousands of lines of code hidden from you by the object. You can
simply access this code by calling the method. You can achieve this by using a
single line of script. The term used to describe the approach of hiding complex
code is encapsulation.
Invoking a method
There are three different ways to invoke a method. Which approach you use in
your script depends upon how the method is exposed. The three approaches are
described below.
Syntax Object.Method
In this approach, the method is invoked with a simple call. The call uses the dot
notation to specify the name of the object and the name of the method that you
want to invoke. In this simple call, the method does not need any inputs from
your script, nor does it return data to your script.
6 Module 2: Working with Objects
In this approach, the method is invoked with a call similar to the previous call.
Again, the call uses the dot notation to specify the name of the object and then
the name of the method that you want to invoke. However, this approach passes
data into the method from your script by using one or more parameters. The
method accepts the data and works with it internally, encapsulated from your
script.
The parameters are provided as a comma-separated list.
Syntax MyVariable = Object.Method([Param1, Param2, … ,Paramn])
In this approach, a Visual Basic Scripting Edition variable is used to hold the
return value of the method call. Again, the dot notation is used, but this time the
value of the variable is set to the result of the method call.
Note For more information about variables, see Using Objects later in this
module and in Module 3, “Script Logic,” in Course 2433A, Microsoft Visual
Basic Scripting Edition and Microsoft Windows Script Host Essentials.
Using Parentheses
An important addition to this syntax is the inclusion of the parentheses that
follow the method call. The parentheses indicate that your script must evaluate
the method call. In this case, it holds the evaluated data in the variable.
Methods that return data to the calling script might require parameters. If this is
the case, then those parameters must be supplied as a comma-separated list
inside the parentheses, as shown in the previous syntax. However, some
methods might return data and not require parameters. If this is the case, then
you still must use the parentheses, although the code does not contain any
parameters, as the following syntax illustrates:
Syntax MyVariable = Object.Method()
Properties
Objects expose their data to your script in their properties. To manipulate this
data, all you must know is how to retrieve and set the property value. You do
not need to know how the object actually stores or handles the data. Again, this
reinforces the black-box reuse concept.
The following syntax illustrates some standard approaches to setting and
retrieving the values of an object’s properties:
Module 2: Working with Objects 7
In this syntax, using the dot notation sets the property's value. The value might
take one of a number of forms, but you must be able to evaluate it as a discrete
value. Some of forms that the value takes are described as follows:
A literal value
You can set the property of an object to a literal value, such as the number
10 or the string “Cat.”
A simple expression that can be evaluated as a discrete value
You can set the property of an object to the result of an expression that your
script can evaluate as it runs, such as the result of 18 + 9 or the result
“London” concatenated with “ United Kingdom.”
A property of another object
You can set the property of one object to the property of another object. You
can achieve this in the following single line of code:
Syntax Object1.Property1 = Object2.Property2
If you want to retrieve the property value and store it in one of your variables,
use the following code. The syntax is very similar to that used to retrieve the
return value of a method. However, in this case, you do not use parentheses.
Syntax MyVariable = Object.Property
8 Module 2: Working with Objects
Classes
A class is the blueprint for an object. The developers who allow you to reuse
their code as objects do not write the code in the object itself. They actually
write code in a class. When you want to reuse code, your script creates an
object based on a class. The object code is written in the class in such a way
that it provides you with the methods and properties for your object.
The blueprint makes allowances that alarms can be installed and furniture can
be added. These actions are analogous to methods. The object is manipulated
after it has been created by performing these actions.
Furthermore, the blueprint of the building does not specify a fixed color for the
paint used to decorate it. The blueprint allows this color to be chosen after the
building has been constructed. The paint color is analogous to a property.
Type Libraries
A type library is a collection of classes that can be redistributed to allow you to
build objects based on those classes. Type libraries are compiled files that
expose their classes to your script. They are usually compiled into dynamic link
libraries (DLL) or ActiveX Controls files.
A Collection of Classes
Using the earlier analogy of a blueprint, the architect might produce many
blueprints for different building types. She might develop one blueprint for a
house, one for an apartment building, and one for a skyscraper office complex.
She might then store all of these blueprints in a folder that is named Buildings.
When she completes these blueprints, she can give the whole folder to the
builder. When the builders want to build a house, they can get the house
blueprint from the folder. They could also access the skyscraper or apartment
blueprints to construct those types of buildings, as well.
In this analogy, the folder is the type library. It contains the blueprints for many
different types of buildings. Each building type has its own set of distinct
features and attributes. In object terminology, the methods and properties are
these distinct features and attributes.
You must know the name of any type library that you use in your scripts.
Note For examples of the names of type libraries, see Working with Objects
later in this module.
Instantiation
The process of creating an object from its class is termed instantiation. When an
object is instantiated, it inherits the properties and methods that the class
defines. This functionality is held in memory by your computer. As a result, it
is efficient for you to manipulate the object.
After the object is instantiated, it no longer needs to refer back to its class, nor
is it desirable that it should do so. The premise behind this fact is that after the
object is created, you can manipulate it without affecting the class upon which
the object was based.
Using the architect drawing analogy, imagine that the builders have constructed
a house and that the decorator paints it yellow. It is sensible that this action
should affect only that house and should not affect the blueprint. If it does
affect the blueprint, then all of the new houses would now be yellow, which is
obviously not desirable.
10 Module 2: Working with Objects
Multiple Instances
You will often use multiple instances of the same class in your script. If you
create multiple instances of the same class, then you can manipulate each
instance, or object, independently of the others.
Using the above analogy, the builders might construct a whole street of houses
from the same blueprint. The decorator might then paint house Number 1
yellow. This will not affect the other houses, even though they are based on the
same blueprint. The decorator might paint house Number 2 green, and so on.
Note Objects are usually instantiated with a single line of code written in
Visual Basic Scripting Edition. For more information about how to write this
instantiation code, see Creating and Using Objects later in this module.
Module 2: Working with Objects 11
Creating Objects
Topic Objective
To explain how to create
objects.
Lead-in Libraries
The type library that Example-Wshom.ocx
Windows Script Host uses is
Wshom.ocx. Classes
Example-WScript.Network
Object Usage Example
Dim
Dim oNetwork
oNetwork
Set
Set oNetwork
oNetwork == CreateObject(“WScript.Network”)
CreateObject(“WScript.Network”)
oNetwork.MapNetworkDrive
oNetwork.MapNetworkDrive "z:",
"z:", \\London\Lab2Share
\\London\Lab2Share
Libraries
The WSH library is distributed in the Wshom.ocx file, and is installed by
default on all Microsoft Windows 2000 computers.
This type library is accessed in a script that uses the following name:
Example WScript
Classes
The WScript type library contains multiple classes that you use in your scripts.
An example is the Network object. This allows a script to perform simple
network tasks. The object is instantiated using the following syntax:
Syntax Set <Object Variable> = CreateObject("<Library>.<Class>")
The above syntax uses the CreateObject() function that is part of the Visual
Basic Scripting Edition language. It accepts a string parameter that specifies the
type library and the class to be used to create the object. An object variable is
set to the result of this function so that you can then use the variable to refer to
the newly created object in subsequent lines of script.
Note For more about object variables, see Using Objects later in this module.
Module 2: Working with Objects 13
After this object has been instantiated, you can use the object to perform
network tasks, such as mapping a network drive or printer. This is achieved by
using methods, such as MapNetworkDrive and AddPrinterConnection. The
oNetwork object variable also exposes properties such as ComputerName and
UserName, which you can use in the script to identify the user running the
script and the computer that it is running on. The following example illustrates
how you can use these methods and properties:
Example Set oNetwork = CreateObject("WScript.Network")
oNetwork.MapNetworkDrive "Z:", "\\MyServer\MyShare"
Wscript.Echo oNetwork.ComputerName
The first line of code instantiates the new object and sets the oNetwork object
variable to it.
The next line of code uses the MapNetworkDrive method to create a new drive
mapping. The parameters supplied indicate that the Z drive is to be mapped to
the shared folder called MyShare on the server called MyServer.
The third line of script retrieves the value of the ComputerName property from
the oNetwork object variable. In the same line of code, the result of this
operation is displayed to the user with the Echo method of the built-in WScript
object.
Note Although WScript is the name of a type library, there is also an object
called WScript that exposes useful methods like Echo. Since this object is
related to the host itself, there is no need to instantiate it (as you must do with
most objects). It is automatically instantiated by the host that your scripts run in
and can therefore be used directly.
14 Module 2: Working with Objects
Using Objects
Topic Objective
To explain how you can
create and use objects in
scripts. Assigning an Object to a Variable
Lead-in Set
When you want to use an Set objFSO
objFSO == CreateObject("Scripting.FileSystemObject")
CreateObject("Scripting.FileSystemObject")
object in a script, you must
first create the object by Using an Object
using the set statement.
objFSO.CreateFolder("C:\Test")
objFSO.CreateFolder("C:\Test")
Deleting an Object
Set
Set objFSO
objFSO == Nothing
Nothing
Using an Object
After the object has been created in the memory space of the running script, it is
possible to access the methods and properties that it exposes by using the object
variable that points to it.
The following example uses the CreateFolder method to create a new folder
called Test in the root of the C drive:
Example objFSO.CreateFolder ("C:\Test")
Module 2: Working with Objects 15
Deleting an Object
Objects consume memory on the computer that they are running on. Therefore,
it is good practice to delete them when you are done using them.
To delete an object, you set its object variable to the keyword Nothing, as
shown in the following:
Example Set objFSO = Nothing
Note Objects that are not explicitly set to Nothing are deleted automatically by
WSH when the script terminates. However, it is considered best practice to
delete objects explicitly when the script no longer requires them, because this
frees up the disk space that is used by the object. Complex objects can use a
substantial amount of disk space, so you should delete complex objects as soon
as possible.
16 Module 2: Working with Objects
COM Objects
Topic Objective
To introduce the concept of
COM objects.
Lead-in Data Marshalling
WScript
The Component Object
Model provides a set of Contract
rules that defines how
software can be made of
reusable components. What Can You Do?
VBScript
Contracts
A contract consists of a definition of the methods and properties supported by
objects. COM allows a contract to be defined and specifies the services that the
component provides to its clients. The rules of COM mandate that the contract,
after it is published or made generally available to client software, cannot
change. This alleviates many of the versioning issues prevalent in most
software systems, particularly those developed prior to the component era.
COM also governs how data is transferred between the client and object. The
process of passing data into and out of an object is called marshalling.
Object Identification
The ProgID is stored in the HKEY_CLASSES_ROOT section of the registry.
It tells the system which .dll, .exe, or .ocx file contains the associated class
definition that is used to construct the object. A ProgID consists of a type
library and a class name that are separated by a dot, as in the following
example:
Syntax Library.Class
Automation
Scripting environments, such as WSH, impose certain restrictions on COM
objects. One of the key restrictions is the range of data types that can be passed
to and from the object. This, and other restrictions, means that script code
cannot communicate with all COM objects. Those COM objects complying
with the requirements of script are called automation objects.
Automation defines a restricted set of data types and imposes one or two other
requirements on the developer of COM objects. From the administrator’s
perspective, this is not a significant issue, since nearly all of the object models
that an administrator might want to use from a WSH script are automation-
compliant.
Module 2: Working with Objects 21
Type Libraries
As mentioned previously, you can use type libraries to define the set of classes,
methods, and properties that a component supports. This type of information is
the component’s metadata, the data that describes data.
Although it is typically saved as part of the component’s .dll or .ocx file, it can
reside in a stand-alone type library file, usually with a .tlb file extension. By
examining the metadata inside a type library, it is possible to discover the
objects, methods, and properties that you can use in a script. Object browsers
can use this type information to depict a graphical view of an object model.
22 Module 2: Working with Objects
Note Another browser tool called the object linking and embedding
(OLE)/COM Object Viewer ships with Microsoft Visual Studio® development
system. It is a developer-oriented tool and will not be used in this course.
You can download it as a stand-alone application from the Microsoft Web site
at www.microsoft.com.
Module 2: Working with Objects 23
TextStream
FileSystemObject
You can use the FileSystemObject object to manage files and folders on the
local computer. In addition to manipulating existing folders and files, the
FileSystemObject object enables you to create new folders and text files.
You can only create text files by using the FileSystemObject object. If you
want to create a new Word document, you must use the Word object model.
The FileSystemObject object also does not provide support for managing
NTFS file systems permissions. If you need to change the security permissions
on the file, you must use an extra utility.
Dictionary
The Dictionary object is a container object that you can use to store arbitrary
items of data. You associate each item with a name or unique key value. You
can use the key to retrieve the stored data.
For example, you can use the Dictionary object to store the details about all of
the administrators in an enterprise. Details might include a name, phone
number, and e-mail address. You can associate each dictionary entry with the
unique site the administrator is responsible for.
The site in the following example acts as the key with which the data item can
be retrieved. It uses the Dictionary object. The example creates an instance of
the Dictionary object and then stores the details of three administrators, Alan,
Kathie, and Don, in it.
26 Module 2: Working with Objects
To display, for example, the details about the administrator who is responsible
for the UK, use the following line of code. This line of script uses the
associative feature of the Dictionary object to retrieve the detail about the UK
administrator. The retrieved data is then concatenated with a string literal and
displayed by using the WScript.Echo method.
Example WScript.Echo "The UK administrator is: " & AdminsList("UK")
Encoder
Scripts that have been encoded use the Encoder object. The encoding process
is done with the Windows Encoder utility. This enables script writers to encode
their script so that the script cannot be viewed, copied, or modified but can still
be executed.
Module 2: Working with Objects 27
Environment
WScript
The WScript object is an intrinsic object, which means that it is automatically
created when a script is executed and requires no explicit instantiation. The
WScript object supports the following methods:
CreateObject. This enables the creation of an object for use in the script.
Shell
This object is instantiated with the following statement:
Example Set objShell = WScript.CreateObject("WScript.Shell")
You can use this object to start a new process, create shortcuts, and provide the
environment collection to handle access to useful environmental variables, such
as WINDIR, COMPUTERNAME, and USERNAME. This is done by using the
following objects:
SpecialFolders. Returns the paths for Windows shell folders such as the
Desktop folder, Start menu folder, and personal My Documents folder.
Shortcut. Creates an object reference to a shortcut.
UrlShortcut. Creates an object reference to a Uniform Resource Locator
(URL) shortcut.
Environment. Retrieves environment variables from the operating system.
Network
This object is instantiated with the following statement:
Example Set objNetwork = WScript.CreateObject( "WScript.Network" )
CDO Names
CDO has gone through the following name changes in its lifetime:
Previous versions of CDO were called OLE Messaging. OLE Messaging
was first available in Exchange version 4.0.
CDO version 1.1 was named Active Messaging. Active Messaging was
installed with Exchange version 5.0. There were a few feature
enhancements in Active Messaging, but the core functionality of the library
remained unaltered.
The current version 1.2 has the name Collaboration Data Objects (CDO).
CDO 1.2 is installed with Exchange version 5.5. This version has added
functionality over CDO 1.1, including support for scheduling meetings and
appointments.
Data Sources
Data sources are often relational databases, such as SQL Server 2000. However,
ADO enables you to access a variety of other nonrelational data sources, such
as Active Directory. You can use ADO to search Active Directory for objects
and properties, such as users and phone numbers. Because it enables you to
search Active Directory, ADO is of interest to administrators who write scripts.
Note The current ADO provider for ADSI only provides read-only access to
objects in Active Directory.
Note For more information about how to use ADO to search for information in
Active Directory, see Module 5, “Understanding ADSI,” in Course 2433A,
Microsoft Visual Basic Scripting Edition and Microsoft Windows Script Host
Essentials.
34 Module 2: Working with Objects
ADSI compatible products include Active Directory, Exchange 5.5, IIS, and
Site Server.
Note You will learn more about ADSI in Module 5, “Understanding ADSI”.
Module 2: Working with Objects 35
Note This level of functionality makes WMI complex to script. WMI scripting
is a major topic on its own and falls outside the scope of this course. For more
information about WMI scripting, see Module 8, “Beyond the Basics” in
Course 2433A, Microsoft Visual Basic Scripting Edition and Microsoft
Windows Script Host Essentials.
For more information about WMI in general, go to the following Web site and
download the WMI software development kit (SDK):
http://msdn.microsoft.com/downloads/c-frame.htm?007#/downloads/sdks.
Module 2: Working with Objects 37
Internet Explorer
Since Microsoft Internet Explorer version 3.0, Internet Explorer has had a
scripting host embedded in it. Due to this historical link with the Web browser,
a great deal of VBScript documentation still assumes that you are using script
only in the context of a Web browser.
This may be misleading for systems administrators, because the functionality
provided by WSH could be very different to that provided by Internet Explorer.
For example, the functionality of the Internet Explorer host has been limited for
security reasons, because it is not desirable if a remote Web script can access
the FileSystemObject object and delete files or folders.
IIS
IIS has the ability to run VBScript if this script is embedded in an Active Server
Page (ASP). Unlike Internet Explorer, the ASP page has full access to WSH,
because the script is being run only on the server. As a result, ASP pages can be
used very successfully to provide a central management Web site that
administrators can use to manage an enterprise.
Note For more information about the administrative use of ASP pages, see
Module 8, “Beyond the Basics,” in Course 2433A, Microsoft Visual Basic
Scripting Edition and Microsoft Windows Script Host Essentials.
38 Module 2: Working with Objects
Other Applications
Topic Objective
To introduce the use of
scripting in other
applications. Microsoft Office
Lead-in Microsoft Word, Microsoft Excel, Microsoft PowerPoint,
Because many applications
expose their own COM
Microsoft Access, Microsoft Outlook, and Microsoft
interface, can control them FrontPage
through the use of script.
Utilities
Example: Windows Media Player
Microsoft Office
It is possible to control Microsoft Word, Microsoft Excel, Microsoft
PowerPoint®, Microsoft Access, Microsoft Outlook, and Microsoft FrontPage®
with script. A comprehensive help file is included with Microsoft Office to help
you understand the many possibilities involved in scripting these applications.
The help file is aimed at Visual Basic and Web developers, so some
experimentation with different versions of the examples might be needed to
make them work with WSH.
Note For examples of scripting with Microsoft Office, see Module 8, “Beyond
the Basics,” in Course 2433A, Microsoft Visual Basic Scripting Edition and
Microsoft Windows Script Host Essentials.
Utilities
Many utilities also expose a COM interface, which makes scripting possible.
The Microsoft Windows Media™ Player is an example of such a utility. To find
the possibilities for scripting these utilities, use the Object Browser and
examine the object model for the program that you want to script. This shows
you the object, methods, and properties that you can use in your scripts.
Module 2: Working with Objects 39
Objectives
After completing this lab, you will be able to:
Manipulate the scripting object model by using Visual Basic Scripting
Edition.
Manipulate the WSH object model by using VBScript.
Automate Microsoft Office applications by using VBScript.
Scenario
In this lab, you will use VBScript to manipulate various object models.
Specifically, you will instantiate objects from the scripting object model, the
WSH object model, and the Microsoft Word object model. You will then
manipulate the methods and properties of these objects to perform
administrative tasks.
Exercise 1
Manipulating the Scripting Object Model
In this exercise, you will write code in Visual Basic Scripting Edition that
manipulates the scripting object model. You will instantiate a
FileSystemObject object and a Folder object and manipulate them by using
their methods and properties.
You have now concatenated the drive property of the Folder object to a
string literal. The script written in VBScript joins them together and then
uses them as a parameter for the WScript.Echo method. The whole line of
code should read:
WScript.Echo "The Folder's Drive is: " & oFolder.Drive
Module 2: Working with Objects 41
3. Locate the comment TODO Retrieve the Path property of the Folder
object.
4. Add the following code to the end of the line immediately below this
comment:
& oFolder.Path
You have concatenated the path property of the Folder object to a string
literal. The script written in VBScript joins them together and then uses
them as a parameter for the WScript.Echo method. The whole line of code
should read:
WScript.Echo "The Folder's Path is: " & oFolder.Path
5. Locate the comment TODO Retrieve the Count property of the Folder
object's Subfolders collection.
6. Add the following code to the end of the line immediately below this
comment:
& oFolder.SubFolders.count & " subfolders"
Tip The line continuation character () indicates that the text following it
should be written on the same line as the code that precedes it.
Exercise 2
Manipulating the WSH Object Model
In this exercise, you will write code in Visual Basic Scripting Edition that
manipulates the WSH object model. You will instantiate a Shell object and a
Network object and manipulate them by using their methods and properties.
3. Locate the comment TODO Use the Shell's RegRead method to read
values from the Registry.
4. Type the following lines of code immediately below this comment:
sOS = oShell.RegRead("HKLM\Software\Microsoft\
Windows NT\CurrentVersion\ProductName")
nBuildNo = oShell.RegRead("HKLM\Software\Microsoft\
Windows NT\CurrentVersion\CurrentBuildNumber")
sOrg = oShell.RegRead("HKLM\Software\Microsoft\
Windows NT\CurrentVersion\RegisteredOrganization")
These three lines of code retrieve data from the registry and store them in
VBScript variables.
Note There are only three lines of code for you to type. The continuation
arrows indicate that the subsequent code should be typed on the same line as
the preceding code.
Exercise 3
Automating Microsoft Word
In this exercise, you will write code in Visual Basic Scripting Edition that
manipulates the Microsoft Word object model. You will instantiate an
Application object. You will create and modify a Document object. You will
then save the Document object and review its contents.
wRange.Style = -3
wRange.Font.Color = 255
wRange.Text = sContent
wDoc.SaveAs "C:\Automating Word.doc"
wApp.Quit
Tip This code uses the following three objects from the Microsoft Word
object model:
• An Application object, which is Microsoft Word itself
• A Document object that is saved to the hard disk
• A Range object that allows the text of a document to be manipulated
Note that the value -3 indicates a Microsoft Word style of Heading 2 for the
Range object. Also note that the value 255 indicates that the text is red. All
of this information can be obtained by using the Object Browser.
Review
Topic Objective
To reinforce module
objectives by reviewing key
points Object Terminology
Lead-in Creating and Using Objects
The review questions cover
some of the key concepts Understanding Object Models
taught in the module.
Common Object Models
4. What object model provides access to the Windows Shell and Network
objects?
The WSH object model.
Module 3: Script Logic
Contents
Overview 1
Fundamental VBScript Rules 2
Variables, Constants, and Data Types 4
Operators 22
Conditions and Loops 28
Procedures 41
Script Layout 48
Lab 3: Working with VBScript 56
Review 63
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 3: Script Logic iii
Instructor Notes
Presentation: This module provides students with an introduction to the most commonly used
60 Minutes features of the Microsoft® Visual Basic® Scripting Edition (VBScript)
language.
Lab:
30 Minutes After completing this module, students will be able to:
Describe the rules of the VBScript language.
Declare and use variables, constants, and data types in their scripts.
Use VBScript language operators.
Construct conditional code structures.
Construct looping structures.
Declare and use Sub and Function procedures.
Determine an effective script layout.
Required Materials
To teach this module, you need the following materials:
• Microsoft PowerPoint® file 2433A_03.ppt
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
iv Module 3: Script Logic
Module Strategy
Use the following strategy to present this module:
Fundamental VBScript Rules
This section provides the basic VBScript syntax. It is a single-slide topic, so
do not spend too much time on it. Make sure, however, that the students
understand everything in this section, because it is prerequisite knowledge
for the subsequent sections.
Variables, Constants, and Data Types.
This is an extremely important section. Make sure that the students fully
understand the topics in this section, because they will use variables,
constants, and data types in the lab for this module and in all subsequent
labs.
Do not cover issues of scope or lifetime for variables in this section, because
they are covered in detail in the Procedures section later in the module.
The students may struggle to understand the concept of multidimensional
arrays, so use the graphics on the slide to help them visualize these data
structures.
Operators
Make sure that the students understand all of the operators provided by
VBScript.
Use the topic Class Discussion: Operators to open a class discussion. Ask
the students to evaluate each expression in the notes. Since all of the
expressions are similar, ask them to note carefully the order of precedence
of the operators that are used.
Conditions and Loops
To successfully write useful administrative scripts, the students must
understand the conditional and looping structures, as they are covered in this
section.
Make sure that all of the students understand the concepts behind this sort of
programming. It is essential that they understand, because the lab for this
module and the rest of the course relies on the students' ability to write this
type of code.
Procedures
Discuss Sub and Function procedures, as they are covered in this section.
Stress that the primary difference between the two types of procedures is
that Function procedures return a value to the calling code, while Sub
procedures do not.
This section also includes a topic that deals with the scope and lifetime of
variables. Make sure that the students understand the importance of these
concepts.
Be aware that the students may find it difficult to visualize the difference
between ByRef and ByVal when passing parameters to procedures. If
necessary, explain the examples in the text, line-by-line, to ensure that the
students fully understand the implications of these two approaches to
passing data into a procedure.
Module 3: Script Logic v
Script Layout
This last section deals with some recommendations for developing
manageable code templates and administrative scripts. Emphasize to the
students that they can develop a scheme that suits their particular needs.
The section finishes with some basic best practice recommendations. Again,
the students are free to code as they wish, but point out the advantages of
the points made in this topic.
vi Module 3: Script Logic
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Training and
Certification courseware.
Lab Setup
There are no lab setup requirements that affect replication or customization.
Module 3: Script Logic 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Fundamental VBScript Rules
Variables, Constants, and Data Types
Lead-in
In this module, you will learn Operators
about the VBScript
language. Conditions and Loops
Procedures
Script Layout
This gives the scriptwriter flexibility when laying out the script in a manner
that is easy to read.
VBScript does not impose a maximum line length.
Unlike other languages, such as Microsoft Visual Basic, VBScript does not
impose a maximum number of characters per line. In addition, you can write
what are effectively separate lines of code on a single line by using the
colon as a divider. The following combines two logical lines by using the
colon divider:
Module 3: Script Logic 3
VBScript enables you to type a line of code over several lines in the script.
Long statements can be broken into multiple lines by using the line-
continuation character (a space followed by an underscore). Using this
character can make the script easier to read. The following example shows a
long line of code split into four lines by line-continuation characters:
Example WScript.Echo "Message to " _
& vUserName & _
" Please lock your workstation"
If you split a long string across multiple lines, you must manage the string
data on each line as a separate string. You can achieve this by ending each
string with double quotes, and then concatenating the subsequent string to
the previous line by using the string-concatenation character (&). The
following example illustrates how to split a string across multiple lines:
Example WScript.Echo "Message to" _
& vUserName _
& " Please make sure that you remember" _
& " to logoff or lock your workstation" _
& " if you leave it unattended, Thanks"
Variables
Topic Objective
Containers for Values That May Change
To describe variables.
Value is accessible by the variable name
Lead-in
Variables are names that String Data
you define, which point to
memory locations that your strServer = "MyServer"
script can access. Dates and Times
dDOB = #05-06-1966#
Naming Restrictions
Declaring Variables
Implicit or explicit?
Option Explicit
In this example, you manipulate the variable nMyAge by retrieving its current
value and adding 10 to it. The new value is then echoed to the screen. The
scriptwriter does not need to know the value of nMyAge in advance. In fact, a
user could provide it to the script at run time through a pop-up box. Variables
that contain a single value, such as nMyAge, are described as scalar variables.
String Data
A string is a data type that indicates that the variable contains characters, rather
than numeric values. To store string data in a variable, you must enclose the
data in double quotes as shown in the following example:
strServer = "MyServer"
Example
6 Module 3: Script Logic
This indicates that the script written in VBScript interprets the value as a date or
time, rather than as a string or a calculation, such as 5–6–2000.
Naming Restrictions
When naming variables in Visual Basic Scripting Edition, the following rules
apply. A variable name:
Must begin with an alphabetic character.
Cannot contain an embedded period.
Must not exceed 255 characters.
Must be unique within the current scope.
Note A variable cannot be assigned the name of a VBScript keyword. For a list
of VBScript keywords, see the VBScript documentation.
Declaring Variables
By default, script written in Visual Basic Scripting Edition implicitly creates a
variable the first time that it reads a name that is not a reserved word or
procedure name. This sort of behavior can easily result in script errors due to
mistyped variable names.
In the following example, the scriptwriter has mistakenly typed nMiAge
instead of nMyAge on the second line. The result of this typographical error is
that instead of echoing a value of 45, as expected, a value of 10 is returned. This
is because the script written in VBScript implicitly created a new variable
called nMiAge. It is initialized with a value of zero.
Example nMyAge = 35
nMyAge = nMiAge + 10
WScript.Echo nMyAge
This type of error can be very difficult to trace, so it is considered good practice
to force the script written in VBScript to require explicit variable declarations
by using the following line at the top of the script:
Example Option Explicit
After the Option Explicit command has been added to the script, any
undeclared variables will cause the script to generate an error rather than
implicitly create a variable.
Module 3: Script Logic 7
After Option Explicit has been added, you must explicitly declare all new
variable names before they can be used. You can declare variables by using any
of the following statements:
Dim
Private
Public
Static
You will see the difference between these statements later in this module. You
can use all of the statements to declare the name of the variable and reserve
some memory to hold the value of the variable; for example:
Example Dim nMyAge
Constants
Topic Objective
To describe constants.
Lead-in
As well as declaring and
Constants Do Not Change During Script Execution
using variables in your Makes scripts easier to read and debug
scripts, you can declare and
use constants. Assigned at the start of the script
The CONST Statement
Const COMP_NAME = "Microsoft"
Type Library Constants
Intrinsic Constants
Examples: vbCrLf , vbRed
If you attempt to change a constant’s value in the script, the script written in
Visual Basic Scripting Edition generates the following compilation error:
Example Microsoft VBScript compilation error: Name redefined
Module 3: Script Logic 9
The type library itself declares the above constant and assigns it a value of 2.
Visual Basic and Microsoft Visual C++® provide support for directly
referencing the type library. This enables developers to use the predefined
constants in their code.
Visual Basic Scripting Edition is unable to read information directly from a
type library.
Note Microsoft Windows® Script Host (WSH) version 2.0 provides Extensible
Markup Language (XML) support in .wsf files. This enables you to reference
type library constants.
For further details, see Module 8, “Beyond the Basics”, in Course 2433A,
Microsoft Visual Basic Scripting Edition and Microsoft Windows Script Host
Essentials.
This line declares the following constant and assigns it the value of 2:
ADS_GROUP_TYPE_GLOBAL_GROUP
The &H tells the script that this is a hexadecimal value so that it is stored
correctly. In this instance, &H2 is the same as a decimal value of 2. If the value
is &H32, the decimal value stored by the script is 50. After this definition is in
place, you can use the more meaningful constant name.
10 Module 3: Script Logic
Note These constant values are published in the Microsoft Windows 2000
Platform software development kit (SDK). A quick way to find the value is to
search for the constant name or search for ENUM for a list containing all the
enumerations available.
Alternatively, if you know the type library that exposes the constants, you can
use the Object Browser to discover the values directly. For example, the ADSI
constants are stored in activeds.tlb, which has a Programmatic Identifier
(ProgID) of ActiveDs.
For more information about ADSI constants, see Module 5, “Understanding
ADSI,” in Course 2433A, Microsoft Visual Basic Scripting Edition and
Microsoft Windows Script Host Essentials.
Intrinsic Constants
Along with the constants that are defined by the scriptwriter, there are a number
of useful constants built into Visual Basic Scripting Edition. These constants,
referred to as intrinsic constants, provide a convenient way to use specific
values without having to remember the value itself. Because these constants are
already defined in VBScript, there is no need to explicitly declare them in the
script. You can simply use them in place of the values that they represent.
Note Because it is not possible to disable intrinsic constants, the names of the
constants are treated as reserved words.
For a full list of these intrinsic constants, refer to the VBScript documentation.
The following table illustrates the various categories of constants and a brief
description of each.
Constant grouping Definition
Color Constants Defines eight basic colors that can be used in scripting.
For example, vbRed represents the number 255, which
is interpreted as red.
Date and Time Constants Defines date and time constants that are used by
various date and time functions. For example,
vbMonday represents the value 2, vbSunday equals 1,
and vbTuesday equals 3.
Date Format Constants Defines constants used to format dates and times.
Miscellaneous Constants Defines constants that do not conveniently fit into any
other category.
MsgBox Constants Defines constants used in the MsgBox function to
describe button visibility, labeling, behavior, and
return values.
String Constants Defines a variety of nonprintable characters that are
used in string manipulation.
Tristate Constants Defines constants that are used with functions that
format numbers.
VarType Constants Defines the various Variant subtypes.
Module 3: Script Logic 11
This constant represents the value of Chr(13) and Chr(10), which are the ASCII
characters for the carriage return and line-feed characters. This is useful when
formatting the text that is displayed in a message box as follows:
Example sMessage = "Welcome to the world of VBScript" & vbcrlf & _
"and all the useful commands that it provides" & _
vbcrlf & "Please press the OK button to continue"
MsgBox sMessage
The first line assigns the message string to a variable called sMessage. Then,
the MsgBox function displays the string as three lines of text rather than one
long line.
12 Module 3: Script Logic
Data Types
Topic Objective
To describe data types.
Lead-in
VBScript uses one data type
Variants
for all data. Variant Subtypes
Empty Null Boolean
Byte Integer Currency
Long Single Double
Date (Time) String Object
Error
Conversion Functions
Variants
A Variant can contain numeric data, dates and times, objects, Boolean
variables, or strings. In most cases, VBScript will automatically detect the type
of data stored and will deal with it accordingly.
In the following example, vAnswer contains the string "MyServer," because
vDemoA and vDemoB contain string values declared in quotes. The addition
operator in this example performs a string concatenation.
Example vDemoA = "My"
vDemoB = "Server"
vAnswer = vDemoA + vDemoB
WScript.Echo vAnswer
The next example looks very similar, but the vDemoA and vDemoB variables
contain numeric data. This time, the result of the addition operation generates
another number. As a result, vAnswer holds data that is numeric.
Example VDemoA = 5
vDemoB = 10
vAnswer = vDemoA + vDemoB
WScript.Echo vAnswer
Module 3: Script Logic 13
Variant Subtypes
It is possible to divide the Variant data type into subtypes. These subtypes
allow a finer level of control on how data is manipulated by your script.
For example, you can have numeric data that represents currency, a date, or a
time. The Variant interprets the data accordingly.
A Variant contains many subtypes, as illustrated in the following table.
Subtype Description
Conversion Functions
Sometimes, a strict level of control over the exact data type is required. In these
situations, you can use conversion functions to convert data from one subtype
to another.
A typical example of when this might be required is when you extract a
particular set of digits from a number. This is much easier to achieve by using
string handling functions such as Left, Right, and Len. To use these functions,
the numeric value must first be converted to a string by using the CStr
function. After the digits have been extracted, you can then convert them back
into an integer by using the CInt function.
The following table lists the functions that can convert data into a Variant of a
specific subtype.
Function name Conversion
Note For more information about conversion functions, see the VBScript
documentation.
Module 3: Script Logic 15
Naming Conventions
Topic Objective
To introduce naming
conventions.
Lead-in Not Required, but Good Practice
It is a good idea to employ a Hungarian Naming Convention
naming standard for your
variables and constants. Prefix names with a type identifier
Example: Wscript.Echo objMyServer.Name
Constants must be capitalized
Be Consistent
str String
Fn Function
c (or capitalize each letter in the
Constant
constant name)
b Boolean (True or False)
d Date
obj An object reference
n A numeric value
16 Module 3: Script Logic
Function, method names, and each word in a multiword name should begin
with a capital letter, as the following examples show:
Example WScript.Echo objMyServer.Name
VBScript now has a Const command but this format has become the
preferred naming standard for constants.
Note There is a great deal more to this naming convention, most of which is
not relevant to scripting due to the limited data types available to script. For
more information about this subject, go to:
http://msdn.microsoft.com/library/partbook/win98dh/
variablenameshungariannotation.htm
Be Consistent
You do not have to use the Hungarian naming convention. You can easily
develop your own naming convention. For example, you can use dtm as the
prefix for dates and times. However, whatever naming standard you use, it is
important that you apply it consistently in all scripts. This will aid in the
reading and debugging of the scripts in the future.
Module 3: Script Logic 17
Arrays
Topic Objective
To describe arrays. A Variable That Can Contain Multiple Values
Lead-in
VBScript provides powerful
Dim MyArray(2) 0 1 2
support for arrays. Accessing the Values in Array Variables
MyArray(0) = 100
WScript.Echo MyArray(1)
Multidimensional Arrays
Dim MultiDArray(1,3,2) 2
1
3
0 2
1
0
0 1
The number is known as the upper bound of the array. The array can store
discrete values by using any number between zero and the upper bound,
including zero and the upper bound itself. Therefore, it can store a number of
values that is one greater than the upper bound.
The next example retrieves the value in the second element (element number
one) and uses it as a parameter to the Echo method of the WScript object:
Example WScript.Echo MyArray(1)
Multidimensional Arrays
It is possible to have multidimensional arrays. You declare a multidimensional
array by providing a comma-separated list of upper bounds, as the following
example shows:
Example Dim MyTable(4, 9)
This example shows two numbers being used as the upper bounds, which
indicates that this is a two-dimensional array. You can visualize a two-
dimensional array as a table. The following table is a representation of how you
can visualize the two-dimensional array.
0 1 2 3 4 5 6 7 8 9 10
0
1
2
3
4
5
You can use up to 60 dimensions for an array in Visual Basic Scripting Edition.
An array with three dimensions can be visualized as a cube. It becomes harder
to visualize an array with four or more dimensions. However, most arrays you
will use in VBScript will have no more than four or five dimensions and will
often contain only one or two.
Note Arrays can contain variables of different data types. This is useful if you
are storing values related to the same object. For example, the first value can be
a person’s name, and the rest of the row can be the values relating to that
person, such as a telephone number. The next row can be the next person.
Module 3: Script Logic 19
Dynamic Arrays
Topic Objective
To describe dynamic arrays. Creating Dynamic Arrays
2. Initialize the array to the required size by using the ReDim statement.
Example ReDim MyArray(4)
You can use ReDim on its own to create and initialize an array in one step.
3. Use the array as in the previous section, Arrays.
20 Module 3: Script Logic
Resizing an Array
The ReDim statement can also be used to resize the array if required. For
example, you may start with an array that has five elements, but at some point,
it may need to be resized to hold eight values. You can reissue the ReDim
statement, as the following example shows:
Example Dim MyArray()
RedDim MyArray(4)
MyArray(0)=100
MyArray(1)=200
MyArray(2)=300
MyArray(3)=400
MyArray(4)=500
...
...
ReDim MyArray(7)
...
...
Caution If you resize a fully populated array so that it contains fewer elements
than before, then you will inevitably remove some data, even if you use the
Preserve keyword.
Module 3: Script Logic 21
The Dim statement declares the variable name. The variable is then converted
into an array, initialized to contain five elements, and populated with the values
shown in the parentheses, all in one line. Note that the statement does not
require an upper bound to be explicitly declared. The upper bound of the array
will be created to fit the number of elements in the parentheses.
Emptying an Array
The Erase statement is used to delete the contents of an array.
Example Erase MyArray
This clears the contents of a fixed-size array. The array itself still exists.
However, if using the Erase statement empties a dynamic array, the data is
removed and the array is uninitialized. The array must be redimensioned with
the ReDim statement before it can be used again.
In this syntax, arrayname is the name of the array, and dimension is the
required dimension that you want to check. If only one dimension exists,
dimension is optional.
22 Module 3: Script Logic
Operators
Topic Objective
To introduce operators.
Lead-in
In this section you will learn
Operators
about the operators that Class Discussion: Operators
VBScript provides.
Operators
Topic Objective
To describe operators.
Lead-in
Operators are used to
Main Operator Types:
manipulate variables and Arithmetic: ^ - * / \ Mod + -
values in your script.
Concatenation: &
Comparison: = <> < > <= >= IS
Logical: Not And Or XOr Eqv Imp
Operator Precedence
Parentheses
Arithmetic Operators
Arithmetic operators perform basic arithmetic functions such as addition,
subtraction, or multiplication. The following table describes the arithmetic
operators.
Operators Description Symbol
Concatenation Operator
You often must create a string by concatenating or joining together two or more
other strings. The string concatenation operator is the ampersand (&). A space
must follow the ampersand for the concatenation to work correctly. For
example, the following script sample concatenates two string literals and a
string variable into a single string that is then echoed to the screen:
Example WScript.Echo "The path is, " & strPath & " on Server B"
In this example, the variable nAge is assigned the value entered into the input
box. A simple calculation is then done to calculate the years left until the age of
65. The result is stored in the variable nTogo. This number is then concatenated
with two string literals, and the resulting string is displayed in a message box.
Warning It is possible to use the plus sign (+) to provide concatenate strings.
However, this is not recommended because it will generate errors when mixing
string and numeric values.
Comparison Operators
Comparison operators are used to compare values. By using these operators, an
expression can be built that will test for a condition and return either True or
False. The following table describes the available operators.
Description Symbol
Equality =
Inequality <>
Less than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
Object equivalence IS
Logical Operators
Logical operators are used in a similar way to comparison operators. For
example, the Not operator performs logical negation on an expression as
follows:
Example bNegResult = Not bResult
Operator Precedence
You will often build complex tests by using a mixture of operators. It is
important to understand how the various operators are resolved and the order in
which each part of the expression is evaluated. This is determined by the order
of operator precedence that VBScript defines.
The following list presents the operators in the order of precedence that is
defined by VBScript:
^
–
*, /, and \
MOD
+, -
&
=, <>, < >, <=, >=, and IS
NOT
AND
OR
XOR
EQV
IMP
____________________
(1+4+10)*6-(4/2)
____________________
1+4+10*(6-4)/2
____________________
(1+4+10) & (6-4)/2
____________________
1+4+10 & 6-4/2
____________________
28 Module 3: Script Logic
Code
If…Then
You will often use the If…Then statement in Visual Basic Scripting Edition,
because it provides a simple test to evaluate if a condition is True or False. The
basic syntax for the If…Then structure is:
Syntax If <condition> Then <action>
For example:
Example If MyVar = 5 Then WScript.Echo "MyVar = 5"
In this example, the message MyVar = 5 is echoed to the screen only if the
MyVar variable contains the value 5. If the variable has any other value, the
message will not be displayed.
Else
The Else statement can be added to the If…Then statement. This enables
statements to be executed if the condition within the If statement is not met; for
example:
Example If MyVar = 5 Then
WScript.Echo "MyVar = 5"
Else
WScript.Echo "MyVar does not equal 5"
End If
30 Module 3: Script Logic
In this script, the message MyVar does not equal 5 is displayed unless the
MyVar variable contains the value 5.
Note The expansion of the structure from the single-line syntax, shown
previously, to the multiple-line format, as shown in this example, is known as a
Block If structure. When you develop Block If structures, you must always
remember to include the keyword End If at the end of the structure.
ElseIf
The ElseIf construct extends the functionality of the If statement by allowing
the condition to have more than two different results; for example:
Example If MyVar = 0 Then
WScript.Echo "MyVar = 0"
ElseIf MyVar = 1 Then
WScript.Echo "MyVar = 1"
ElseIf MyVar = 2 then
WScript.Echo "MyVar = 2"
Else
WScript.Echo "Sorry value is out of range"
End If
End If
The End If statement can be added if you want to combine multiple steps in a
single test. For example:
Example If MyVar = 5 Then
WScript.Echo "MyVar = 5"
WScript.Echo "Reseting MyVar"
MyVar = 0
End If
In this example, three lines of script are executed if the condition evaluates to
True. These lines are indented for clarity. Indentation is particularly beneficial
when several conditional statements are nested, as shown in the following
example:
Example If MyVar = 5 Then
WScript.Echo "MyVar = 5"
If MyVar2 = 10 Then
WScript.Echo "MyVar2 = 10"
End If
End If
If MyVar contains the value 5, the first message is echoed to the screen. Then, a
second test is performed on a second variable. If that also returns True, a
second message is displayed. An End If statement is required for each If
statement.
Module 3: Script Logic 31
? Code
? Code
This script is clearer than the previous example that uses the If…Then…ElseIf
structure. Notice that substituting an If...Then...ElseIf structure with a Select
Case structure only works in this example, because the same condition is being
tested all the way down the ElseIf tree. If more than one condition is being
tested, the If…Then structure is more appropriate.
Select Case statements can be nested. Like the If statement, each nested Select
Case statement must have a matching End Select statement.
32 Module 3: Script Logic
Looping: For…Next
Topic Objective
To describe For…Next
loops.
For…Next Initialize Loop
Lead-in
You often must write code Exit For
that runs multiple times in
Code
each execution of your
script. Exit Loop?
For Each…Next Code
Collections
Arrays Loop? ? Exit Loop?
For…Next
The For...Next loop is used to execute one or more statements a specific
number of times. The number of times that the statements are executed is
determined by the counter variable of the For…Next loop, which is set up
when the loop is initialized. This counter is then increased or decreased with
each repetition of the loop.
The syntax of the For…Next construct is:
Syntax For counter = start to finish [Step n]
action(s)
Next counter
For example, the following code illustrates a loop that runs ten times:
Example For iCounter = 1 To 10
WScript.Echo "This is loop number " & iCounter
Next
Module 3: Script Logic 33
This Step statement results in only five iterations of the loop. As the loop runs,
iCounter has the value of 1, 3, 5, 7, and 9.
The Step statement can also be used to decrement a counter simply by the
addition of a minus sign (-).
Example For iCounter = 10 to 2 Step -2
action(s)
Next
In this example, the loop is iterated five times, starting at the value of 10 and
finishing with the value of 2.
Exit For
You can optionally exit a loop at any time before it is finished by using the Exit
For statement; for example:
Example vInput = InputBox ("Enter the Value to stop the loop at")
iStop = CInt(vInput)
For iCounter = 1 to 10
WScript.Echo "Current iCounter Value = " & iCounter
If iStop = iCounter Then Exit For
WScript.Echo "Around we go again"
Next
WScript.Echo "Loop exited at value of " & iCounter
This script uses a variable called vInput that takes a value from the user of the
script. This value is then converted into an integer and stored in the iStop
variable. A For…Next loop is then set up and the current value of the counter
variable iCounter is echoed to the screen. A test is then done to see if iCounter
equals iStop. If it is equal, the loop is exited. Otherwise, a message is echoed,
and the loop continues. After the loop is exited, a message is echoed that
displays the value of iCounter.
34 Module 3: Script Logic
For Each…Next
The For Each…Next structure is used to iterate through the items in a
collection of objects or for each element of an array. This is very useful when
you do not know how many elements there will be in the collection prior to
running the script; for example:
Example For Each File in objFiles
WScript.echo File.Name
Next
The above example shows a snippet of a script that has a collection object
called objFiles. Collection objects usually contain multiple items, so the For
Each…Next structure is used to loop through each item in the collection. In
this example, a collection of files is looped through, and the name of each file is
displayed. Once all of the items in the collection have been displayed, the loop
is exited.
Module 3: Script Logic 35
Do…Loop
The Do…Loop structure iterates a number of script statements in a similar
fashion to the For...Next structure. The main difference between the Do…Loop
structure and the For…Next structure is that the Do…Loop structure does not
require you to know the number of times the loop must be run when you write
the code. There are two basic forms of this structure: Do While…Loop and the
Do Until…Loop.
Do While…Loop
This loop repeatedly executes a statement while a condition is true. The
condition is evaluated each time that the loop begins.
Example Do While vMyVar < 100
vMyVar = vMyVar + 1
WScript.Echo "vMyVar = " & vMyVar
Loop
36 Module 3: Script Logic
Do Until...Loop
This statement repeats the script in the loop until a condition becomes true. The
previous examples can be converted into the Do Until…Loop structure by
making the following changes to the script test conditions:
Example Do Until vMyVar >= 100
vMyVar = vMyVar + 1
WScript.Echo "vMyVar = " & vMyVar
Loop
Do…Loop While
You can check the expression that represents the exit condition at the end of the
Do While loop, rather than at the beginning; for example:
Example Do
vMyVar = vMyVar + 1
WScript.Echo "vMyVar = " & vMyVar
Loop While vMyVar < 100
Checking the condition at the end of the loop, rather than at the beginning,
forces the loop to be executed at least once. Imagine that the condition is
already satisfied when the loop begins. If you check for the condition at the
beginning of the loop, the code inside the loop is not executed at all.
However, if you check the condition at the end of the loop, even if the condition
is already met, the code inside the loop runs once. If, by the end of the loop, the
condition is still satisfied, the loop is finished. However, note that the code
inside the loop may alter the state of the condition. The loop continues until the
condition is satisfied once more.
Do…Loop Until
As with the Do While loop, you can check the expression that represents the
exit condition at the end of the Do Until loop, rather that at the beginning; for
example:
Example Do
vMyVar = vMyVar + 1
Example WScript.Echo "vMyVar = " & vMyVar
Loop Until vMyVar >= 100
Module 3: Script Logic 37
Exit Do
Just as there is an Exit For statement, there is an Exit Do statement that is
useful for exiting a loop if another condition is met while the loop is executed.
For example:
Example vInput = InputBox ("Enter the Value to stop the loop at")
iStop = CInt(vInput)
Do While iCounter < 10
iCounter = iCounter + 1
WScript.Echo "Current iCounter Value = " & iCounter
If iStop = iCounter Then Exit Do
WScript.Echo "Around we go again"
Loop
WScript.Echo "Loop exited at value of " & iCounter
While…Wend
The While…Wend structure was introduced in the early days of Visual Basic
and has since been superseded by the Do loops and the For loops. It is available
for backwards compatibility.
It works in the following way:
If the test condition is true, all of the statements in the loop are executed
until the Wend statement is encountered.
The script then returns to the While statement and the test condition is
checked again.
If the condition is still true, the process is repeated.
If it is not true, the loop is exited, and the execution of the script that follows
the Wend statement runs.
For example:
Example While vMyVar < 100
vMyVar = vMyVar + 1
WScript.Echo "vMyVar = " & vMyVar
Wend
Built-in Functions
Topic Objective
To introduce built-in
functions.
Date and Time Functions
Lead-in
VBScript contains a number Now, Time, Date, DateDiff
of special functions that can
be used in your script to String Manipulation Functions
provide certain features that
are very difficult to write
LCase, UCase
yourself. Mathematical Functions
Rnd, Round
Now
The Now function returns the current date and time on the computer system
clock, as the following example shows:
Example WScript.Echo Now
Time
The Time function returns a Variant of subtype Date that indicates the current
time on the computer system clock, as the following example shows:
Example WScript.echo Time
Date
The Date function returns the current date on the computer system clock; for
example:
Example WScript.Echo "Today’s Date is : " & Date
DateDiff
The DateDiff function returns the number of intervals between two dates.
Example vDate = DateDiff("d", Date, "01/01/3000")
WScript.Echo "Days until the next Millennium: " & vDate
The "d" argument indicates that the function must return a number that
represents the number of days between the two dates. Other valid argument
values include:
"yyyy" for the number of years between the two dates.
"m" for the number of months between the two dates.
"h" for the number of hours between the two dates.
Mathematical Functions
Because you often must perform mathematical manipulations with Visual Basic
Scripting Edition, several mathematical functions are provided.
Rnd
The Rnd function returns a random number between 0 and 1 to seven decimal
places. This function only works correctly if the random number generator has
been initialized before the Rnd function is called. To initialize the random
number generator, use the Randomize statement as shown in the following
example:
Example Randomize
WScript.Echo Rnd
By multiplying the value that the Rnd function returns, you can generate
random numbers within a given range. For example:
Example Randomize
WScript.Echo Rnd * 100
Round
If a script requires you to use whole numbers, you can use the Round function
to convert a number to the nearest integer.
Example Randomize
vRnd = Rnd * 100
WScript.Echo Round(vRnd)
Note There are many more functions available in VBScript. For the complete
list of functions, see the VBScript documentation.
Module 3: Script Logic 41
Procedures
Topic Objective
To introduce this section.
Lead-in
In this section, you will learn
Sub and Function Procedures
about Sub and Function Scope and Lifetime
procedures.
Sub Procedures
Sub procedures contain code that you can reuse in your scripts many times
without having to rewrite the code every time that it is needed. Instead, you
write the code once inside the procedure, and then call the procedure from other
places in your code to indicate that the contents of the procedure should be run
at that point.
Module 3: Script Logic 43
The following example shows how Sub procedures can be used in your scripts.
Note that the Sub procedure named Status is called twice. The Call statement is
optional.
Example Dim sStausMessage
Call Welcome
sStausMessage = "Starting..."
Call Status
sStausMessage = "Ending..."
Call Status
Call Farewell
Sub Welcome()
WScript.Echo "Hello"
End Sub
Sub Status()
WScript.Echo sStausMessage
End Sub
Sub Farewell()
WScript.Echo "Goodbye"
End Sub
Function Procedures
Function procedures are very similar to Sub procedures. You write the code
once inside the procedure, and then simply call the procedure from other places
in your code. The only important difference between a Sub and a Function
procedure is that the latter returns a result to the script that called it, while the
former does not.
Consequently, you use the Function procedure most often as part of a larger
expression, because the call to it results in a value being returned in place of the
Function name. The following example illustrate how the function call returns
a value that can be used in any expression:
Example Dim dDate
dDate=Tomorrow
WScript.Echo dDate
Function Tomorrow()
Tomorrow= DateAdd("d",1,Date())
End Function
Exiting a Procedure
If a test, such as an If…Then structure, determines that the procedure must be
exited, the procedure is exited by using the exit statement. When you reach the
end of the procedure, the End Sub statement returns the execution of the script
back to the point in the script immediately after the procedure was called.
44 Module 3: Script Logic
Passing Parameters
The code examples shown so far do not enable you to pass any additional data
into the procedures when they are called. However, passing additional data that
the procedure works with is a very useful and common practice.
To pass parameters to your procedures, you must define the parameters that the
procedure will receive when you write the procedure. You do this by providing
a comma-separated list of parameter names inside the parentheses for the
procedure, as the following example shows:
Example Function GrossValue(NetValue, TaxRate)
GrossValue=NetValue + (NetValue * TaxRate)
End Function
You must pass the values of the parameters to the procedure when you call the
procedure. The following example calls the GrossValue function and passes a
value of 100 for the NetValue parameter and 0.175 for the TaxRate parameter:
Example WScript.Echo "Gross Value is: " & GrossValue(100,0.175)
The second method for parsing an argument is by value. With this approach,
any argument passed to the Sub procedure or Function procedure is a copy of
the original variable. If you make any changes to the parameters in the
procedure, the variable in the calling code is not changed.
To specify this option, you use the ByVal keyword in front of each argument,
as shown in the following example:
Example Function GrossValue(ByVal NetValue, ByVal TaxRate)
GrossValue=NetValue + (NetValue * TaxRate)
End Function
Module 3: Script Logic 45
You will note that in the examples used so far, both ByRef and ByVal result in
identical script behavior. This is because the procedures themselves do not
internally modify the values of the parameters that have been passed to them.
However, this is not always the case. For example, the following code, which
uses ByRef, results in a message of “Two times 60 is 60,” which is obviously
not intended:
Example Dim iNumber, iResult
iNumber=30
iResult = Doubler(iNumber)
WScript.Echo "Two times " & iNumber & " is " & iResult
Function Doubler(ByRef InputNum)
InputNum = 2 * InputNum
Doubler = InputNum
End Function
The InputNum parameter points to the same memory location as the iNumber
variable, because InputNum was passed by using ByRef. Therefore, any
changes made to the InputNum parameter also results in those changes being
applied to the iNumber variable.
The following example is almost identical. However, the parameter is passed by
using ByVal. This results in a message of “Two times 30 is 60,” which is
intended.
Example Dim iNumber, iResult
iNumber=30
iResult = Doubler(iNumber)
WScript.Echo "Two times " & iNumber & " is " & iResult
Function Doubler(ByVal InputNum)
InputNum = 2 * InputNum
Doubler = InputNum
End Function
46 Module 3: Script Logic
Script-Level Variables
When declaring a variable in the main body of the script, it can be referenced
from anywhere else in the script. Variables can be used by other statements in
the main body and also in any procedures that are called. These variables are
known as script-level variables that have script-level scope.
You can declare script-level variables with either the Dim keyword or the
Private keyword. These keywords are synonymous when used to declare
script-level variables.
There is also a Public keyword that can be used to define variables that are
available outside the scope of the script itself. However, you can only do this if
the script is going to be used with other scripts that can reference these
variables, such as .wsf files. If this is not the case, then script-level variables
that are declared with the Public keyword behave identically to variables that
are declared with the Private and Dim keywords.
The names of script-level variables must be unique throughout the script. The
lifetime of a script-level variable is from the time the variable is declared to the
time when the script terminates.
Module 3: Script Logic 47
Procedure-Level Variables
When a variable is declared in a procedure, only script within that procedure
can access or change the value of the variable. It has local scope and is called a
procedure-level variable. A procedure-level variable exists only when the
procedure is running. When the procedure is finished, the variable is destroyed.
The variable has procedure-level lifetime.
You can have local variables of the same name in several different procedures,
because each variable is recognized only by the procedure in which it is
declared. Declaration of procedure-level variables is usually undertaken at the
very start of the procedure itself. This is a good practice, because it makes
tracking the variables easier.
It is also a good practice to declare variables with the smallest scope possible.
This prevents you from having to make a long list of variable names that is
visible to the whole script and helps to minimize the memory that variable
names consume.
Procedure-level variables cannot be declared with the Public or Private
keywords. You must use the Dim keyword to declare procedure-level variables.
48 Module 3: Script Logic
Script Layout
Topic Objective
To introduce script layout.
Lead-in
You can organize your
Script Sections
scripts in a manner that Using a Template
makes them easy to deal
with and easy to read and Best Practices for VBScript
debug.
Script Sections
Topic Objective
To identify the different
sections in a script file.
Lead-in
As your scripts get larger
and more complex, it Script Information Header
becomes increasingly
important to have a
standard and logical layout Initialization Block
for your scripts.
The use of the KEYWORDS field is to enable an indexing engine to search and
retrieve all related scripts.
Initialization block
The next block of the script is the initialization block. In this section, script-
level variables, constants, and object names are declared. This provides a single
reference area where all variable names can be looked up when working on the
script. For example:
Example '==========================================================
'Variable Declarations
Dim nNetValue
'Used to store the net value of a product
Dim nGrossValue
'Used to store the gross value of a product
Dim nTaxRate
'Used to store the tax rate that must be applied to net value
'==========================================================
Module 3: Script Logic 51
'==========================================================
The following example shows the final script, complete with all of the sections:
Example '==========================================================
'
' LANG : VBScript
' NAME : MyScript.wsf
' AUTHOR : My Name
' DATE : 21/06/2000
' Description : Demonstration Script Header
' COMMENT : Add comments here
'
' KEYWORDS : Indexing Keywords here
'==========================================================
'==========================================================
'Variable Declarations
Dim nNetValue
'Used to store the net value of a product
Dim nGrossValue
'Used to store the gross value of a product
Dim nTaxRate
'Used to store the tax rate that must be applied to net value
'==========================================================
'==========================================================
' Main Body
'==========================================================
'==========================================================
' Procedures
' Returns a gross value based on a net value and a tax rate
Function GrossValue(nNet, nRate)
GrossValue=nNet + (nNet * nRate)
End Function
'==========================================================
Module 3: Script Logic 53
Note You can also use another type of layout, which defines the procedures
directly after the initialization of the variables, with the main script logic at the
end of the script. It makes little difference to the execution of the script which
layout you use. Ultimately, it is a matter of personal preference.
54 Module 3: Script Logic
Using a Template
Topic Objective
To provide an example of a
script template.
Lead-in Script Name, Date, Author
After you have defined the Script Description, Keywords
basic script layout, you can
create a template that can Initialize Standard Variables
be reused as the basis for oShell, oNetwork
future scripts.
Script Main Logic
Call Functions/Subs
Note Lab 3, “Working with VBScript,” uses an example script template that
you can customize to meet your needs.
Module 3: Script Logic 55
Objectives
In this lab, you will create a script template file and use it to create a script that
tests a user’s name against a known list.
You will use the following concepts and features of Visual Basic Scripting
Edition to achieve this:
Script templates
Constants
Variables
Decision-making structures
Looping structures
Intrinsic VBScript constants
Procedures
Exercise 1
Creating Script Templates
In this exercise, you will use PrimalSCRIPT to create an administrative script
template.
'==========================================================
'==========================================================
' Main Body
'==========================================================
'==========================================================
' Procedures
End Function
End Sub
'==========================================================
58 Module 3: Script Logic
You have now created a template and have seen how to create a new script that
is based upon it.
Module 3: Script Logic 59
Exercise 2
Using Constants, Variables, Loops, and Conditional Structures
In this exercise, you will use the new file that was written in Visual Basic
Scripting Edition and that was created from the template in exercise 1. You will
then use variables and constants to manipulate data that is entered by the script
user.
In addition, you will create decision-making and looping structures that will
compare the user’s name with a list of pre-approved administrators. You will
enable the user to enter his or her name up to three times. If the user enters an
administrator’s name, the script continues to run. If the user fails to enter a valid
name three times in a row, the user is notified that he or she has not been
validated.
Tip In the text above, the line-continuation characters () are used to
denote that you should type the subsequent code on the same line as the
preceding code. The text has simply wrapped around in the printed
document
2. Immediately below the final End If statement, add the following line to
gather user input and assign it to the variable sUserName:
sUserName = InputBox (
"Please enter your name (firstname lastname)")
To use a Do…Loop
1. Locate the comment Main Body, and on the line immediately below, add a
Do statement as follows:
Do
2. Immediately below the InputBox statement, type the following line of code,
which controls the termination of the loop:
Loop While UCase(sUserName) <> ADMIN_1 _
And UCase(sUserName) <> ADMIN_2
Exercise 3
Using Procedures
In this exercise, you will create a reusable function that carries out the process
of validating a user against a known list of administrators. The function will
return either True or False, thereby making it easy to use in the calling code.
2. Under Main, modify the Loop statement so that it uses the function, as
follows:
Loop While Not Validate(sUsername)
You have now successfully used constants, variables, loops, procedures, and
decision-making code by using Visual Basic Scripting Edition.
Module 3: Script Logic 63
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. Fundamental VBScript Rules
Lead-in Variables, Constants, and Data Types
The review questions cover
some of the key concepts Operators
taught in this module.
Conditions and Loops
Procedures
Script Layout
You have two Block If structures, but only one End If statement.
THIS PAGE INTENTIONALLY LEFT BLANK
Module 4: Error
Handling and
Debugging
Contents
Overview 1
Error Handling 2
Debugging 10
Lab 4: Debugging and Error Handling 15
Review 22
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 4: Error Handling and Debugging iii
Instructor Notes
Presentation: This module provides students with the knowledge they need to write error-
30 Minutes trapping and error-handling code. It also shows them how to debug code to find
logic errors.
Lab:
30 Minutes After completing this module, students will be able to:
Describe the types of errors that may be present in Microsoft® Visual Basic®
Scripting Edition (VBScript) code.
Write code that handles run-time errors.
Use the Microsoft Script Debugger to locate and fix logic errors.
Required Materials
To teach this module, you need the following materials:
• Microsoft PowerPoint® file 2433A_04.ppt
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
iv Module 4: Error Handling and Debugging
Module Strategy
Use the following strategy to present this module:
Error Handling
Use this section to discuss the different types of errors that may be in the
students’ code. Stress that even professional programmers with many years
of experience still encounter errors in their code.
The main focus of this section, however, is the approach available in
VBScript for handling run-time errors.
The section finishes with a complex example of using iterative procedure
calls to implement robust interaction with the user. You must go through
this example step-by-step with the students, because they may find it
difficult to follow on their own. It is crucial that they understand this
example, because they will work with a very similar script in the lab.
Debugging
The focus of this section is on using the features of the Microsoft Script
Debugger.
If you have time available, show the students how the debugger works.
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Training and
Certification courseware.
Lab Setup
There are no lab setup requirements that affect replication or customization.
Module 4: Error Handling and Debugging 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Error Handling
Lead-in Debugging
In this module, you will learn
about error handling and
script debugging.
Error Handling
Topic Objective
To introduce this section.
Lead-in
Even professional
Type of Errors
programmers sometimes Handling Run-Time Errors
encounter errors.
The Err Object
Setting an Error Trap
Types of Errors
Topic Objective
To describe the different
types of errors.
Lead-in Syntax Errors
Programming errors fall into Run-Time Errors
three categories: syntax,
run-time, and logic errors. Logic Errors
Syntax Errors
Syntax errors result from code that is written incorrectly, such as a mistyped
keyword, the omission of required punctuation, or an incorrect construct, such
as a Next statement without a corresponding For statement.
VBScript detects these errors when your script is compiled. If syntax errors are
found, the script cannot start. Instead you will be notified that a compilation
error has occurred. VBScript reports detailed information about the syntax
error, such as its location in your script and a description of the type of error.
Run-Time Errors
Run-time errors occur when your code is syntactically correct, but a statement
attempts an operation that is impossible to execute. For example, attempting a
calculation that includes a division by zero, or attempting to save a file to the
floppy disk drive when no disk is present, results in a run-time error. For these
types of errors, you must create an error trap. You will learn how to create an
error trap in Setting an Error Trap later in this module.
Logic Errors
Logic errors occur when code does not perform the way that you intended.
Your code may be syntactically correct, and no run-time errors may be
encountered, but it does not produce the results that you anticipated. You must
test and debug your code to determine why the results are different than those
that you intended. You will learn how to debug scripts in the Debugging later in
this module.
4 Module 4: Error Handling and Debugging
After the line that performs the division is executed, the script queries the
value of the Err object’s Number property. If it is 0, then no error has
occurred. If it is 11, then you know that a division by zero has been
attempted. A value of 13 indicated that a type mismatch occurred, such as
dividing a number by a string.
The function returns a number to the calling Sub procedure, depending on
the value of the Err object’s Number property. The codes 0, 1, 2, and 3
have been arbitrarily chosen for this script. You can choose to return
whatever data you want to.
Based on the value returned from the function, the MainProc procedure
takes some action. If the value is 1, 2, or 3, an error occurred in the function.
In these cases a suitable message is displayed to the user. The user is then
prompted as to whether he or she wants to try again. If the user answers No,
the script ends.
However, if the user answers Yes, the MainProc procedure calls itself. This
is an advanced technique, known as iterative programming. When you use
iterative programming techniques such as this, you must ensure that the
code does not enter an endless loop.
Function CalcAvg()
On Error Resume Next
Dim intNumberOfTests, intTotalPoints, nAverage
' collect test information
intTotalPoints = InputBox("Enter the Total points scored.")
intNumberOfTests = InputBox("Enter the number of exams.")
' calculate average
nAverage = CInt(intTotalPoints)/CInt(intNumberOfTests)
' check for runtime errors by zero
Select Case Err.Number
Case 0 'No error occurred
WScript.Echo "Average score = " & nAverage
CalcAverage = 0
Case 11 'Division by zero
CalcAvg = 1
Case 13 ' Type mis-match
CalcAvg = 2
Case Else
CalcAvg = 3
End Select
End Function
10 Module 4: Error Handling and Debugging
Debugging
Topic Objective
To introduce this section.
Lead-in
Usually the most difficult
The Microsoft Script Debugger
errors to find and fix are Debugging Techniques
logic errors.
Note You cannot edit the source code directly in the debugger. You must edit
the original .vbs file and then rerun it.
Module 4: Error Handling and Debugging 13
Debugging Techniques
Topic Objective
To describe common
debugging techniques.
Lead-in Setting Breakpoints and Stepping Through Code
The Microsoft Script Using the Command Window
Debugger provides many
features that you can use to Viewing the Call Stack
debug your scripts to find
logic errors.
You can then repeat the procedure for each breakpoint that you want to set in
the document. After you set your breakpoints, you can continue running the
script.
The debugger stops at the first breakpoint that it encounters. You can then use
the stepping options to execute the lines according to your requirements.
14 Module 4: Error Handling and Debugging
Objectives
After completing this lab, you will be able to:
Write run-time error-handling code.
Use the Microsoft Script Debugger.
Find and fix logic errors.
Scenario
In this lab, you will write error-handling code that traps common run-time
errors, such as divisions by zero and type mismatches. These types of errors are
typically caused by invalid user input, so the approach used in the lab is useful
whenever you write code that interacts with users.
You will also use the Microsoft Script Debugger application to find logic errors
and bugs in code written in VBScript. You will see how to fix these errors.
Exercise 1
Trapping Run-Time Errors
In this exercise, you will create and implement a run-time error trap.
4. On the line immediately below this calculation, type the following code:
Select Case Err.Number
Case 0 'No error occurred
Msgbox "Average score = " & nAverage
CalcAvg = 0
Case 11 'Division by zero
CalcAvg = 1
Case 13 ' Type mis-match
CalcAvg = 2
Case Else
CalcAvg = 3
End Select
Exercise 2
Debugging VBScript
In this exercise, you will use the Microsoft Script Debugger to find and fix
logic errors.
You have now successfully debugged a script written in VBScript with the
script debugger.
22 Module 4: Error Handling and Debugging
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. Error Handling
Lead-in Debugging
The review questions cover
some of the key concepts
taught in the module.
3. What are the three stepping options that are supported by the Microsoft
Script Debugger?
Step Into, Step Over, and Step Out.
Module 5:
Understanding ADSI
Contents
Overview 1
ADSI Overview 2
Binding with ADSI 8
ADSI Objects 17
Searching Active Directory 26
Lab 5.1: ADO Search 32
Creating New ADSI Objects 35
Setting Security in Active Directory 41
Managing Shares Using ADSI 43
Controlling Services Using ADSI 45
ADSI Resources 48
Lab 5.2: Scripting Administrative Tasks
Using ADSI 50
Review 58
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 5: Understanding ADSI iii
Instructor Notes
Presentation: This module provides students with the knowledge and practical experience to
90 Minutes write scripts that interact with Active Directory Services Interface (ADSI).
Labs: After completing this module, students will be able to:
60 Minutes
Describe how ADSI works.
Bind to ADSI objects.
Search Active Directory.
Create and modify objects in Active Directory.Manage shares with
ADSI.Control services with ADSI.
Required Materials
To teach this module, you need the following materials:
• Microsoft® PowerPoint® file 2433A_05.ppt
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the labs.
iv Module 5: Understanding ADSI
Module Strategy
Use the following strategies to present this module:
ADSI Overview
Use this introductory section to ensure that the students understand what
ADSI provides. Do not go into too much detail in this section because the
rest of the module provides plenty of in-depth information for the students.
Binding with ADSI
Describe the process of binding, and ensure that the students understand
what occurs in the binding process. Use the examples in this section to
illustrate typical binding code. Stress the importance of server-less binding.
ADSI Objects
Use this section to introduce the objects available to the students' scripts that
interact with ADSI. Discuss how to invoke object methods and how to set
and retrieve the values of object properties
Searching Active Directory
Emphasis how important and useful ADO objects can be to the students
when they need to search Active Directory.
Explain all code examples in this section, line-by-line. Be aware that most
students will not have used ADO before, so make sure that you explain that
it is part of the Microsoft universal data-access strategy.
Creating New ADSI Objects
Use the examples in this section to describe how organizational units (OU),
groups, and users can be easily created by using ADSI.
The students will almost certainly be very interested in creating these types
of objects with script, because it will increase efficiency in their daily tasks.
Setting Security in Active Directory
Use this overview section to introduce the fact that security can be
manipulated by using ADSI scripts. However, make the students aware of
dsacls.exe because they will use this utility to set security at their
workplaces.
Managing Shares with ADSI
Students will almost certainly be very interested in managing shares by
means of script, because it will increase efficiency in their daily tasks. Go
through the examples in this section line-by-line to ensure that the students
understand all of the options available to them when they are writing code
that interacts with shares.
Controlling Services with ADSI
Students should show a strong interest in controlling services by means of
script, because it will increase efficiency in their daily tasks. Go through the
examples in this section line-by-line to ensure that the students understand
all of the options available to them when they are writing code that interacts
with services.
ADSI Resources
Use this section to tell students about other useful ADSI resources.
Module 5: Understanding ADSI v
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Microsoft
Official Curriculum (MOC) courseware.
Important The labs in this module are also dependent on the classroom
configuration that is specified in the “Customization Information” section at the
end of the Classroom Setup Guide for course 2433A, Microsoft Visual Basic
Scripting Edition and Microsoft Windows Script Host Essentials.
Lab Results
There are no configuration changes on student computers that affect replication
or customization.
Module 5: Understanding ADSI 1
Overview
Topic Objective
To provide an overview of ADSI Overview
the module topics and
objectives. Binding with ADSI
Lead-in ADSI Objects
In this module, you will learn
about writing scripts that Searching Active Directory
interact with ADSI.
Creating New ADSI Objects
Setting Security in Active Directory
Managing Shares Using ADSI
Controlling Services Using ADSI
ADSI Resources
ADSI Overview
Topic Objective
To introduce this section.
Lead-in
Before you write code that
What is ADSI?
interacts with ADSI, you Benefits of ADSI
must understand how ADSI
works and how it can help ADSI Architecture
you to create administrative
scripts.
What Is ADSI?
Topic Objective
To provide an overview of
ADSI.
ADSI
Lead-in
ADSI enables you to write The primary interface to Active Directory
code that interacts with Version 2.5 released with Windows 2000
directory services.
Available for Win9x and Windows NT 4.0
Provides Access to Directory Service Objects
Support For Multiple Directory Service Providers
LDAP
Windows NT
NDS
Bindery
ADSI
Microsoft Windows® 2000 ships with ADSI version 2.5, which is also available
as a download for Microsoft Windows NT® 4.0, Microsoft Windows 95, and
Microsoft Windows 98 at the following Web site:
http://www.microsoft.com/ntserver/nts/downloads/other/ADSI25/
This LDAP address refers to the object called Alan in the Organizational
Unit called “Test” in the domain named microsoft.com.
Windows NT (WinNT)
This is the easiest provider to use because of its simple address format. It
provides access to both Windows NT 4.0 and Windows 2000 computers and
domains. The local provider DLL for Windows NT is ADSNT.DLL.
Novell NetWare Directory Services (NDS)
The NDS provider works with Novell Netware version 4.x or greater to give
access to objects in the Novell Directory Service (NDS). The provider DLL
is ADSNDS.DLL.
NetWare 3 Bindery (NWCOMPAT)
Access to the Novell legacy network operating system is achieved through
use of the NWCOMPAT provider. This provider allows ADSI to access
objects stored in Bindery-based servers such as Netware versions 3.11 and
3.12. The provider DLL is ADSNW.DLL.
Module 5: Understanding ADSI 5
Benefits of ADSI
Topic Objective
To describe the benefits of
ADSI.
Ease of Use
Lead-in
ADSI provides several major Namespace Portability
advantages to scriptwriters.
Powerful Functionality
Can script common admin and end-user tasks:
• List all objects in a directory
• Add new objects to a directory
• Manage security on objects in a directory
• Create a network share
• Control machine services remotely
Ease of Use
ADSI exports a comprehensive but straightforward set of interfaces that you
can use to easily access objects within a directory service.
Namespace Portability
ADSI abstracts the complexity of the directory service interfaces, allowing you
to use the same set of methods to access multiple directories. This greatly
simplifies script writing because the basic methods can be reused with different
directory objects in different namespaces.
Powerful Functionality
ADSI provides a set of powerful features that enable you to develop
sophisticated script solutions. These solutions may include simple tasks such as
finding objects in an OU through complex scripts that create entire enterprise
directory services and populate them with many objects.
Note Microsoft used ADSI scripting when testing the scalability of Active
Directory to help create the massive directory structures required.
ADSI Architecture
Topic Objective
To describe the ADSI
Client ADSI Directory
architecture. Script Provider Service
Lead-in 1 Client binds to 2 Provider creates ADSI 3 Directory
Before examining how to a directory object and translates service
script ADSI, it is important to service object ADSI methods into object data
directory service-
service- is retrieved
understand how the ADSI specific API calls
architecture works.
‘VBScript
Option Explicit
Dim oNetwork
Dim oShell
Binding
The ADSI client must first find and connect (bind) to an object. The client can
be an application, such as a script, a custom application, or one of the support
tools supplied on the Windows 2000 CD-ROM.
The Provider
After the client has bound to an object, the ADSI provider DLL on the local
computer processes the bind request from the client and translates it into the
directory-specific API call to retrieve the required object. The client script or
application can then use the methods and properties of the object.
The following steps are involved in this process:
1. The client script or application makes a request to bind to an object in a
directory service.
2. The ADSI provider on the client computer receives the request and creates
an ADSI object in the client’s address space. The provider then makes a
connection to the required directory service by using the API calls of that
particular directory service.
3. The directory service object information, such as the object methods and
properties, are retrieved from the directory.
4. The directory service object information is returned to the ADSI provider.
5. The ADSI provider creates an instance of the ADSI object in the memory
space of the client application.
6. The object methods are now available for the client script to use.
8 Module 5: Understanding ADSI
Binding
Topic Objective
To describe binding. Providers
Lead-in LDAP:, WinNT:, NDS:, NWCOMPAT:
The binding process creates
an object in the client’s ADs:
memory address space.
Bind Syntax
WinNT:
Set
Set <object>
<object> == GetObject("WinNT://Domain/Server/Object,Class")
GetObject("WinNT://Domain/Server/Object,Class")
LDAP:
Set
Set <object>
<object> == GetObject("LDAP://DomainName")
GetObject("LDAP://DomainName")
Examples
Providers
An important part of the binding request from your script is to specify the
provider that should be used to bind to the object. As discussed earlier, ADSI
includes four different providers:
WinNT:
LDAP:
NDS:
NWCOMPAT:
Ads:
There is also an Ads: name that can be used to resolve all of the available
providers on the local computer. For example, if an enterprise uses a new
provider called NewProv, the following code could be inserted into any scripts
that require this non-standard provider:
Example Set objProviders = GetObject("ADs:")
For Each provider In objProviders
If provider.name = "NewProv:" Then
WScript.Echo "The required provider is installed"
WScript.Quit
End If
Next
WScript.Echo "The required provider is missing"
WScript.Quit
Binding Syntax
The ADSI binding syntax for the WinNT provider is as follows:
Example Set <Object> = _
GetObject ("WinNT://Domain/Server/Object,Class")
where:
<Object> is the object variable that will contain the reference to the
retrieved Active Directory object.
GetObject is the method used to bind to the ADSI namespace and create
the local copy of the object that will be used in the script.
“WinNT” is the ProgID for the required ADSI provider. This name is
sometimes referred to as the Moniker. (Moniker is a Component Object
Model (COM) term that describes the mechanism that is used to bind to
COM objects, in this case the ADSI providers.)
“Domain” is the domain name.
“Server” is the computer name.
Object is the object name.
Class is the class specification. This is optional, but it is useful for
preventing ambiguity where different objects have the same names. Using
this class specification can also speed up the binding process.
Together, the provider name and path are referred to as the ADSPath or bind
string.
Module 5: Understanding ADSI 11
Note The preceding example binds to the domain that includes the server. This
differs from the WinNT provider, which binds to the computer object if a
computer name is used.
Note If the computer to which you bind is not a domain controller, the
provider binds to the Security Accounts Manager (SAM) of the local computer.
Server-Less Binding
Topic Objective
To describe server-less
binding.
Preferred Binding Method
Lead-in
It may not always be No hard-coded server name
possible or desirable to bind
to specific computers in your RootDSE Binding
scripts.
No hard-coded domain name
Portable, site-aware, fault-tolerant
Directory Service client required for non-Windows 2000
clients
Global Catalog Server Binding
GC://
RootDSE Binding
The server-less binding approach works well in a single domain environment.
However, if your script is to be run from multiple domains, you must use an
object called RootDSE that eliminates the need for a hard-coded reference to
the domain, as well as the server. You can use the RootDSE object to resolve
the current domain name before binding to it. Each Windows 2000 domain
controller has a unique RootDSE object that you can use to provide information
about the various namespace objects in the domain, which can then be used in
scripts.
Note DSE stands for “DSA-Specific Entry,” where DSA is an X.500 term for
the directory server.
This example displays the name of the domain in which the script is running.
First, the script binds to the RootDSE object. Then, it creates a new object
called oMyDomain that binds to the current domain by using the
DefaultNamingContext property of the RootDSE object. Finally,
WScript.echo displays the domain name.
14 Module 5: Understanding ADSI
The RootDSE object enables the script to be run from any domain and to
successfully receive a binding for the script to use. The following is a list of
some of the most commonly used properties of the RootDSE object on a
Windows 2000 domain controller.
Property Description
Note Clients of Windows 95, Windows 98, and Windows NT cannot use
server-less binding unless they have the Directory Service client installed in
addition to the ADSI Services download.
Any searches performed against this GC server will return all objects in the
forest that match the criteria, including objects from the client’s local domain.
Module 5: Understanding ADSI 15
Note This method requires that the user’s name and password be entered as
clear text into the script. This presents a security issue that you should consider
when planning.
16 Module 5: Understanding ADSI
ADSI Objects
Topic Objective
To introduce this section.
Lead-in
In this section, you will learn
Object Methods
more about the objects Object Properties
available to your scripts.
Demonstration: Using ADSVW.EXE
Object Methods
Topic Objective
To describe object methods. Object
Lead-in
Object methods enable you
to manipulate ADSI objects.
Put, Get
PropertyName
PutEx GetEx
Directory
GetInfoEx Service
SetInfo
The following table lists the seven ADSI object methods that are used to work
with ADSI objects and the local property cache.
Method Description
The following ADSI script example demonstrates the methods that can be used
to read the values of properties that belong to an object in Active Directory.
Example 'Create an instance of an OU object from existing AD OU
Set oOU = GetObject _
("LDAP://cn=Admin10,OU=WST,DC=Microsoft,DC=local")
'Get a value from AD into the Local Property cache (LPC)
WScript.Echo oOU.PropertyCount ' 0 Properties cached
oOU.GetInfoEx Array("memberOf"), 0
WScript.Echo oOU.PropertyCount ' 1 Property cached
'Fill the Local Property Cache
oOU.GetInfo
WScript.Echo oOU.PropertyCount ' all Properties cached
'Get a value from the LCP
WScript.Echo oOU.Get("cn")
'Same as above using different method
WScript.Echo oOU.cn
'Get & echo a multivalued property from Local Property Cache
aMemberOf = oOU.GetEx("memberOf")
For Each grp In aMemberOf
WScript.Echo grp
Next
Next, the GetInfoEX method is used to populate the local property cache with
a single property, memberOf. This is checked by echoing out the property
count once again. The GetInfo method is then used to pull from the directory
all properties that contain a set value. The property count shows the number of
these values now in the local property cache. The next two lines echo the value
of the CN property stored by using two different techniques, the Get method
and the .PropertyName property.
The last method that is demonstrated is GetEx, which is used to access the
values of multivalue properties. This method returns the values of a property as
an array that can then be stepped through in any number of ways. The script
demonstrates the use of a For…Each loop.
The first task of this script is to define the ADSI constants that will be used in
the script. These constants will be used by the PutEx command, which will be
discussed later.
After the instance of the Admin10 user has been created, the script writes a new
value for the Description property, by using the Put method and then the
.PropertyName syntax. Notice that you can use the .PropertyName technique to
both read and write values in ADSI scripting. The PutEx method is then used
to append an extra value into an existing multivalue property. The syntax for
this method is shown in the following example:
Syntax oOU.PutEx ADSProp, "property", Array("Val1", "Val2")
In this example, “ADSProp” is a constant value that is used to indicate how the
value should be updated. It can consist of any of the values in the following
table.
Constant name Value
ADS_PROPERTY_CLEAR 1
ADS_PROPERTY_UPDATE 2
ADS_PROPERTY_APPEND 3
ADS_PROPERTY_DELETE 4
Module 5: Understanding ADSI 21
Object Properties
Topic Objective
Six Standard Properties
To describe object
properties. Name
Lead-in Class
Object properties enable
you to manipulate ADSI Guid
objects. ADsPath
Parent
Schema
Additional Properties Are Specific to the Class Type
Reading Multiple Properties
Script Uses Schema Names, Not Display Names
To create a connection
1. Run ADSVW.EXE from the folder <install folder>\Democode\Mod05.
2. Highlight ObjectViewer.
3. Click OK.
4. In the Enter Ads Path text box, type LDAP://London
5. Click to clear the check box for Use OpenObject and click OK.
You should now see a binding to your domain. Notice the ADsPath that
shows a connection to your server.
Module 5: Understanding ADSI 25
Using these three objects to issue a query against Active Directory involves the
following four basic steps:
1. Establish the connection to the data source by using the Connection object.
2. Execute a command by using the Command object.
3. Create a recordset by using the Recordset object.
4. Read the information in the recordset.
28 Module 5: Understanding ADSI
Note Although it is possible to use Microsoft SQL Server™ syntax for these
queries, this technique is outside the scope of this course. For more information
about this technique, visit http://www.microsoft.com/data/ado/
In this example, “FQADsPath” is the fully qualified name of the starting point
for your search. “Filter” is the list of elements to be included in or excluded
from the search. These elements can be qualified by using the symbols shown
in the following table.
Name Symbol
In this example, the logical AND symbol is used to ensure that the only value
returned belongs to the object category “Person” and the object class “user”.
You can also use wild card characters, such as asterisks, as shown in the
following example:
Example (ObjectClass=*)
Note The search string does not contain any spaces. If a space is included, the
returned results will contain incorrectly formatted data.
Module 5: Understanding ADSI 29
The following list provides explanations for the different parts of the query
string:
Attributes are the required values that will be returned by the search. A
comma separates each attribute. In the above example, these are the users’
name and telephonenumber properties.
Scope refers to the boundary of the search. After the start point has been
declared, the scope determines where the search stops, based on the
following choices:
• Base
Search the object itself.
• OneLevel
Extend the search to the immediate children of the object, but exclude
the base object itself.
• Subtree
Extend the search down to multiple sublevels of the object, and include
the base object.
If no scope is specified, the search will default to a Subtree search.
30 Module 5: Understanding ADSI
This simple addition allows the query to function without the Connection or
Command objects that were used in the previous example. The following is a
complete example of how you can use this approach:
Example ' Create the ADO Recordset Object
Set rs = CreateObject("ADODB.Recordset")
' Open the Record Set based on the arguments
rs.Open "<LDAP://DC=nwtraders,DC=msft>;" _
& "(objectClass=user);name,telephonenumber;subTree" _
, "provider=ADsDSOObject"
Do Until rs.EOF
' Build Result Text
sResultText = sResultText & rs.Fields("Name") & " , " &
rs.Fields("telephonenumber") & vbCrLf
rs.MoveNext
Loop
WScript.Echo sResultText
The disadvantage of this example is that a new connection is created each time
the query is executed. If multiple queries were run in the same script, the
previous example would be more efficient than this one.
32 Module 5: Understanding ADSI
Objectives
After completing this lab you will be able to:
Search through the WST organizational unit.
Return a number of properties of the user objects by using the ADSI LDAP
query syntax.
Scenario
In this lab, you will create scripts that perform searches by using ADSI and
ADO.
Exercise 1
Performing Searches with ADSI and ADO
In this exercise, you will write ADO code that performs searches by using an
ADSI provider.
2. Type the following Dim statements to declare three variables that will be
used to manipulate ADO objects:
To open the RecordSet object and return the results to the user
1. Type the following line of code to create the Recordset object:
Set aRst = aCmd.Execute()
2. Type the following lines of code to loop through the Recordset object and
build a string from its contents:
Do While Not aRst.EOF
sResultText = sResultText _
& aRst.Fields("samaccountname") _
& ", " & aRst.Fields("givenname") _
& ", " & aRst.Fields("sN") _
& ", " & aRst.Fields("telephonenumber") _
& vbCRLF
aRst.MoveNext
Loop
Creating an OU
The following example script shows the process of creating a new OU object in
Active Directory:
Example Set oRootDSE = GetObject("LDAP://RootDSE")
Set oDom = GetObject
("LDAP://" & oRootDSE.Get ("defaultNamingContext"))
Set oOU = oDom.Create("organizationalUnit", "OU=HQ")
oOU.Description = "Company Headquarters"
oOU.SetInfo
The first line in this example creates an object called oRootDSE that returns a
connection to the root object of the directory service.
Using the Get method of the oRootDSE object creates a new object called
oDom. This object references the default-naming context for the domain.
Using the oDom object and the Create method creates a new organizational
object called oOU with the name of “HQ”. A name is a mandatory property.
It is important to remember that the object is not committed to Active Directory
at this point. There is an ADSI object reference on the client that you can use to
set or modify locally cached attributes, such as the Description. To save the
object back to the directory service, the SetInfo method is called.
Module 5: Understanding ADSI 37
To create a user, you need to provide two required properties: the common
name (CN) and the down-level NetBIOS user name.
Note that, in this example, the object is committed back to the directory service
twice. This is because the properties SetPassword and AccountDisabled can
only be used against an object that already exists in the directory. The first
instance of “SetInfo” commits the new user object to Active Directory, and the
second instance sets the password and enables the account.
Group Types
Windows 2000 has the following four basic group types:
Universal groups
Universal groups can contain accounts and groups, except for local and
domain local groups, from any domain in the forest. Universal groups can
also be added to local groups and other universal groups in any domain in
the forest. These groups are only available when Active Directory is in
native mode.
Global groups
Global groups can contain only accounts and other groups from its own
domain. These groups can be added to global, local, and universal groups in
all domains in the forest.
Domain local groups
Domain local groups can contain accounts and global and universal groups
from any domain in the forest, as well as other domain local groups from the
same domain. They can only be included in access-control lists of the same
domain in which they were created, and can only be a member of other
domain local groups in the same domain.
Local groups
Local groups exist only in the local computer’s Security Access Manager
(SAM). They can only be manipulated on that computer, and can contain
users and groups from any domain in the forest. On domain controllers, this
type of group maps straight onto the domain local group type.
Module 5: Understanding ADSI 39
Method Description
Creating Groups
The following example shows how you can create groups using ADSI:
Example ' Setup Constants
Const ADS_GROUP_TYPE_GLOBAL_GROUP = &H2
Const ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = &H4
Const ADS_GROUP_TYPE_LOCAL_GROUP = &H4
Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &H8
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &H80000000
' Bind to OU
Set oOU = GetObject("LDAP://OU=WST,DC=NWTraders,DC=MSFT")
' Create new group
Set oGroup = oOU.Create("group", "CN=Script Users")
' Set the group type
oGroup.Put "groupType", ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP Or _
ADS_GROUP_TYPE_SECURITY_ENABLED
' Set the group properties
oGroup.Put "sAMAccountName", "Script Users"
oGroup.Put "name", "Script Users"
oGroup.Put "displayName", "Script Users"
oGroup.Put "description", "Script Users Security Group"
' Save back to the AD
oGroup.SetInfo
40 Module 5: Understanding ADSI
In this script, the ADSI constants are declared first. Next, the script binds to the
Users container in the NWTraders.msft domain. Then, a new group called
“Script Users” is created by using the Create method of the oOU object. The
Put method is then used to add the following information to the new group:
The group type
The NetBIOS sAMAcountName
The display name
The description
Finally, the SetInfo method writes this information from the object’s local
cache back to Active Directory.
ADSI Constants
The constants (and their values) that are used in the group creation process are
listed in the following table.
Constant Value
ADS_GROUP_TYPE_GLOBAL_GROUP &H2
ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP &H4
ADS_GROUP_TYPE_LOCAL_GROUP &H4
ADS_GROUP_TYPE_UNIVERSAL_GROUP &H8
ADS_GROUP_TYPE_SECURITY_ENABLED &H80000000
If you are adding multiple users, you can specify additional accounts as shown
in the following:
Example oGroup.Add ("LDAP://cn=MyUser,ou=WST,dc=NWTraders,dc=msft,
LDAP://cn=MyUser2,ou=WST,dc=NWTraders,dc=msft,
LDAP://cn=MyUser3,ou=WST,dc=NWTraders,dc=msft")
Security Components
Each object in Active Directory has a corresponding security descriptor that
enables you to modify and propagate permissions on the object, perform
auditing, and so on.
Each security descriptor has two Access Control Lists (ACL). The first is the
Discretionary ACL (DACL) and the second is the System ACL (SACL). The
DACL contains all administrator-assigned permissions for the object. The
SACL is used to track changes to Active Directory in the security event log of
the domain controller for audit purposes. Each ACL can contain Access Control
Entries (ACE).
An ACE contains the following components:
AccessMask
AceType
AceFlags
Trustee
Flags
Properties:
Name
CurrentUserCount
Description
HostComputer
MaxUserCount
Path
The following example demonstrates how to enumerate all of the shares from a
computer called MyComputer:
Example Set oLMServer=GetObject("WinNT://MyComputer/LANMANSERVER")
For Each share in oLMServer
WScript.Echo share.Name & " = " & share.Path
Next
Note This object currently has no methods that allow you to set permissions
that will apply to the share. One possible solution to this could be to use the
Windows 2000 Resource Kit utility Permcopy. See the Resource Kit
documentation for more details.
Module 5: Understanding ADSI 45
Enumerating Services
The first step in managing services is to enumerate the existing services on a
computer, as shown in the following example:
Example Option Explicit
Dim objComputer, Service, strSvrList
Set objComputer = GetObject("WinNT://MyServer")
strSvrList = "The Services on " & objComputer.ADsPath _
& " are " & vbCrLf
For Each Service in objComputer
If Service.Class = "Service" Then
strSvrList = strSvrList & Service.Name & vbCrLf
End If
Next
WScript.Echo strSvrList
This example binds to the server MyServer and then creates a string variable,
strSvrList, which is used to hold the list of services. A For…Next loop is then
set up to loop through all of the elements in objComputer. For each of these
elements, an If…Then statement tests if the Class of the element is of the type
Service. If it is, it is added to the strSvrList variable. After all of the elements
have been tested, the For…Next loop exits, and the strSvrList variable is
echoed.
46 Module 5: Understanding ADSI
To return only the services that are currently running, you can add a test of the
services’ status. The following list of constants can be used when testing for the
status of these services:
ADS_SERVICE_STOPPED = &H1
ADS_SERVICE_START_PENDING = &H2
ADS_SERVICE_STOP_PENDING = &H3
ADS_SERVICE_RUNNING = &H4
ADS_SERVICE_CONTINUE_PENDING = &H5
ADS_SERVICE_PAUSE_PENDING = &H6
ADS_SERVICE_PAUSED = &H7
ADS_SERVICE_ERROR = &H8
The following is an example of a script returning only the services that are
running on the computer MyServer:
Example Option Explicit
Const ADS_SERVICE_RUNNING = &H4
This script works in the same way as the previous example script, but an extra
If…Then statement has been added to test that the status of a service is equal to
ADS_SERVICE_RUNNING before its name is appended to the strSvrList
string.
Starting a Service
If the name of the required service is known, the process of starting the service
is very simple, as the following example shows:
Example Set oBrowser = GetObject("WinNT://MyServer/browser")
oBrowser.start
Stopping a Service
Similarly, stopping a known service is very simple, as shown in the following
example:
Example Set oMessenger = GetObject("WinNT://MyServer/messenger")
oMessenger.stop
In this example, the object is called oMessenger, and the Stop method is used
to stop the messenger service.
In real-world scripting, it is a good practice to also use the Status method to
check that the service started or stopped correctly before terminating the script.
48 Module 5: Understanding ADSI
ADSI Resources
Topic Objective
To provide further sources Platform SDK
of information about ADSI
scripting. ADSI Resource Kit
Lead-in Microsoft ADSI Web Site
If you require more
http://www.microsoft.com/adsi
information about ADSI, you
will find additional material MSDN Library
in the following places.
http://msdn.microsoft.com/library/Default.asp
Microsoft Scripting Web Site
http://www.microsoft.com/scripting
Microsoft Newsgroup
news://microsoft.public.active.directory.interfaces
MSDN Library
The MSDN® Library site provides access to an online version of the Windows
2000 Platform SDK, as well as Knowledge Base and technical articles that can
be very useful for providing script examples.
Module 5: Understanding ADSI 49
Microsoft Newsgroup
Microsoft maintains a moderated public newsgroup dedicated to ADSI issues at
news://microsoft.public.active.directory.interfaces
50 Module 5: Understanding ADSI
Objectives
After completing this lab, you will be able to:
Create scripts that bind to the domain by using several different methods.
Manipulate various objects by using the ADSI interface.
Scenario
In this lab, you will create scripts that bind to the domain by using several
different methods. You will also create and manipulate various objects, such as
users and groups, by using the ADSI interface. These are common tasks that
will help you to administer your domains.
Lab Setup
To complete this lab, you need a student number. See the “Student Numbers”
section of the lab for this information.
Module 5: Understanding ADSI 51
Student Numbers
The following table provides the computer name, IP address, and student
number of each student computer in the fictitious domain nwtraders.msft.
Find the computer name or IP address assigned to you, and make a note of the
student number.
Computer name IP address Student number
Vancouver 192.168.x.1 1
Denver 192.168.x.2 2
Perth 192.168.x.3 3
Brisbane 192.168.x.4 4
Lisbon 192.168.x.5 5
Bonn 192.168.x.6 6
Lima 192.168.x.7 7
Santiago 192.168.x.8 8
Bangalore 192.168.x.9 9
Singapore 192.168.x.10 10
Casablanca 192.168.x.11 11
Tunis 192.168.x.12 12
Acapulco 192.168.x.13 13
Miami 192.168.x.14 14
Auckland 192.168.x.15 15
Suva 192.168.x.16 16
Stockholm 192.168.x.17 17
Moscow 192.168.x.18 18
Caracas 192.168.x.19 19
Montevideo 192.168.x.20 20
Manila 192.168.x.21 21
Tokyo 192.168.x.22 22
Khartoum 192.168.x.23 23
Nairobi 192.168.x.24 24
Exercise 1
Retrieving Properties Using ADSI
In this exercise, you will write code that interacts with ADSI.
2. Type the following statements to declare the variables that will be used to
manipulate ADSI objects:
Tip The line continuation character () indicates that the subsequent code
should be typed on the same line as the preceding code
2. Type the following lines of code to display the property names and values in
two message boxes:
On Error Resume Next
If iCount Mod 2 = 0 then
For iLoop = 0 To (iCount/2)-1
Set sProp = oMyDomain.Item(CInt(iLoop))
sPropName = sProp.Name
sPropList = sPropList & sPropName & ": " _
& oMyDomain.Get(sPropName) & vbCrLf
If err.number <> 0 then
err.clear
sPropList = sPropList & sPropName & ": " _
& "<MultiValued>" & vbCrLf
End If
Next
WScript.Echo sPropList
sPropList=""
For iLoop = (iCount/2) To iCount-1
Set sProp = oMyDomain.Item(CInt(iLoop))
sPropName = sProp.Name
sPropList = sPropList & sPropName & ": " _
& oMyDomain.Get(sPropName) & vbCrLf
If err.number <> 0 then
Err.Clear
sPropList = sPropList & sPropName & ": " _
& "<MultiValued>" & vbCrLf
End If
Next
WScript.Echo sPropList
sPropList=""
Else
For iLoop = 0 To (iCount/2)-0.5
Set sProp = oMyDomain.Item(CInt(iLoop))
sPropName = sProp.Name
sPropList = sPropList & sPropName & ": " _
& oMyDomain.Get(sPropName) & vbCrLf
If err.number <> 0 then
Err.Clear
sPropList = sPropList & sPropName & ": " _
& "<MultiValued>" & vbCrLf
End If
Next
WScript.Echo sPropList
sPropList=""
Exercise 2
Creating OUs, Users, and Groups Using ADSI
To create a new script
1. On the File menu, click New.
2. In the New dialog box, click Text, and then click OK.
2. Type the following statements to declare the variables and constants that
will be used to manipulate ADSI objects:
Const ADS_GROUP_TYPE_GLOBAL_GROUP = &H2
Const ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = &H4
Const ADS_GROUP_TYPE_LOCAL_GROUP = &H4
Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &H8
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &H80000000
Dim oMyDomain, oRootDSE, oOU, grp, oUSR, sDomainADSPath
Important Remember to substitute your student number where you see “X”.
For example, StudentXOU becomes Student24OU if you are Student 24.
Review
Topic Objective
To reinforce module ADSI Overview
objectives by reviewing key
points. Binding with ADSI
Lead-in ADSI Objects
The review questions cover
some of the key concepts Searching Active Directory
taught in the module.
Creating New ADSI Objects
Setting Security in Active Directory
Managing Shares Using ADSI
Controlling Services Using ADSI
ADSI Resources
2. Before you can use ADSI to work with the objects in a directory, what
action must your script perform with an ADSI provider?
Your script must bind to an ADSI provider.
4. When you work with the properties of an object, where are the updates
being stored?
Local properties cache.
5. How are changes committed back to the directory from the local properties
cache?
The SetInfo method is called.
Module 6: Creating
Logon Scripts
Contents
Overview 1
Verifying the WSH Environment 2
Common Logon Script Tasks 11
Lab 6.1: Creating Logon Scripts 28
Managing Logon Scripts 33
Troubleshooting Logon Scripts 42
Lab 6.2: Assigning Logon Scripts 47
Review 51
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 6: Creating Logon Scripts iii
Instructor Notes
Presentation: This module provides students with the knowledge and practical experience to
45 Minutes successfully write logon, logoff, startup and shutdown scripts for Microsoft®
Windows® 2000.
Labs:
90 Minutes After completing this module, students will be able to:
Check that the correct version of Microsoft Windows Script Host (WSH) is
installed.
Call logon scripts from batch files.
Accomplish common tasks in logon scripts.
Assign logon scripts to users.
Describe common issues with logon scripts.
Describe best practices for using logon scripts.
Required Materials
To teach this module, you need the following materials:
• Microsoft PowerPoint® file 2433A_06.ppt
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the labs.
iv Module 6: Creating Logon Scripts
Module Strategy
Use the following strategy to present this module:
Verifying the WSH Environment
This section is intended to give the students all of the necessary information
and guidance for ensuring that WSH is installed and ensuring that it is the
correct version. This is important, because their scripts may not work
otherwise.
Ensure that the students fully understand all of the points in this section.
Common Logon Script Tasks
This section describes the most common tasks that the students will need to
write logon scripts for.
Describe each task in detail. Be aware that some of the tasks have been
described in previous modules as examples of what can be achieved in
script. This section, however, should be used to delve into the details of
these tasks, so do not skim over these topics just because they have been
mentioned before.
Managing Logon Scripts
This section should be used to explain the various ways that scripts can be
assigned to users, groups, and computers. Make sure that the students
understand the sequence associated with the script time windows, as
explained in this section.
Emphasize the need for securing both the WSH environment and the
contents of script files.
Troubleshooting Logon Scripts
This single-slide section describes some of the most common problems that
the students may encounter with their scripts in the work environment.
Discuss each point as an introduction to the types of issues that the students
may encounter in the real world.
Best Practices
This single-slide section outlines some good practices. Discuss each
recommendation with the students.
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Training and
Certification courseware.
Important The labs in this module are also dependent on the classroom
configuration that is specified in the Customization Information section at the
end of the Classroom Setup Guide for course 2433A, Microsoft Visual Basic
Scripting Edition and Microsoft Windows Script Host Essentials.
Lab Setup
There are no lab setup requirements that affect replication or customization.
Module 6: Creating Logon Scripts 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Verifying the WSH Environment
Lead-in Common Logon Script Tasks
In this module, you will learn
about the use of logon Managing Logon Scripts
scripts and how you can
create and use them to Troubleshooting Logon Scripts
configure a user
environment or a computer’s
environment.
Install WSH Y
Call the
Logon Script
Script Runs
To test for these files, you can use the If Exist…statement, as shown in the
following example:
Example Rem Test places file is usually found
If exist C:\WINNTPRO\system32\wshom.ocx goto :FoundFile
If exist C:\WINNTPRO\wshom.ocx goto :FoundFile
If exist C:\WINNTPRO\system\wshom.ocx goto :FoundFile
Rem No file found install latest WSH in quite mode
Ste51en /q
:FoundFile
Rem The file was found a version of WSH is installed
Rem Now launch the WSH version testing script
CScript //I //nologo WshVerTest.vbs
Tip To make the process of using batch files easier, you can use the Start
command to launch the logon batch file in a minimized window, as shown
below:
START /MIN LOGON.BAT
6 Module 6: Creating Logon Scripts
Using Script
You can check the version of WSH by using the properties of the WSH object
model and the script engine. The following example tests for the version of
WSH:
Example nVer = WScript.Version
If nVer = 5.1 Then
WScript.Echo "WSH Version is OK"
WScript.Quit(0)
Else WScript.Echo "WSH needs updating"
WScript.Quit (1)
End If
The following example checks the version of the Microsoft Visual Basic®
Scripting Edition engine that processes the script:
Module 6: Creating Logon Scripts 7
By updating line 4 of this script, you can check the date that the file was
originally created as follows:
Example If ofile.DateCreated = "07/12/1999 12:00:00" Then
Note While this example works on all computers running Windows 2000
Professional it fails on all others, because the file date is the time that the
original media image was compiled. Therefore, different times and dates are
returned for all versions of Windows 2000 and for the down-level clients
running the downloaded WSH update. You should modify this example
accordingly if you encounter this issue.
8 Module 6: Creating Logon Scripts
Note Microsoft Windows Millennium Edition (Me) has version 5.1 of the
hosts and version 5.5 of the script engines.
For clients running Windows 95 or Windows 98, this is more complex. These
clients do not make the %LOGONSERVER% variable available.
10 Module 6: Creating Logon Scripts
To solve this problem, you can use the %0 variable. This variable returns the
full path of the script that is running. If you add \..\ to the path that is returned
by the %0 variable, the batch process uses the folder that the file is being run
from. As long as the script file is in the same folder as the running file, usually
the logon server’s NETLOGON share, this batch file can call a script file that
works from any platform. The following example shows the use of these
variables:
Example CScript %0\..\LogonScript.vbs
Module 6: Creating Logon Scripts 11
Sending Messages
Topic Objective
To introduce how to send
messages to users. WScript.Echo
Lead-in Echoes to command line in CScript.exe
You can include messages
in logon scripts, and the MsgBox
messages will be displayed
to the user each time that Opens a message box.
the script runs.
PopUp
UserName
WScript.Echo
If the host running the script is WScript.exe, the WScript.Echo method
displays output in a dialog box. If the host running the script is WScript.exe,
the Wscript.Echo method displays output in the command console.
MsgBox
You can use the MsgBox function in Visual Basic Scripting Edition if you want
to display a message in a pop-up message box. This opens a message box in
Windows when either script engine is used, even if the batch mode switch (//B)
has been declared.
The MsgBox function also enables you to display various types of message
boxes, with different button configurations and icon settings. For example, the
MsgBox function can display any of the following icons in the message box:
Critical Message
Warning Query
Warning Message
Information Message
Module 6: Creating Logon Scripts 13
In addition, you can specify the buttons that you want to present in the message
box. You can use the following combination of buttons:
OK only
OK and Cancel
Yes and No
Yes, No, and Cancel
Abort, Retry, and Ignore
Retry and Cancel
The MsgBox function accepts the buttons argument, which you can use to
specify both the icons and the buttons for the message box.
The following table lists the possible values for the buttons argument. Note
that you can use the intrinsic VBScript constants in place of the values to read
and write the script more easily.
Constant Value Description
To specify both an icon and a set of buttons, you can add the numbers or
constants together, as shown below:
Example MsgBox "OK button and Info Icon", vbOKOnly + vbInformation
PopUp
The WSH object model provides a method that enables you to display a pop-up
window. The PopUp method of the WScript.Shell object has features similar
to the MsgBox function, but the PopUp method adds a time value that governs
how long a message is displayed before it is dismissed automatically. The
syntax is:
Syntax oShell.Popup(Text, [Secs2Wait], [Title], [Type])
Text is the body of the message, Secs2Wait is the number of seconds that the
message is displayed, Title is the title bar message, and Type is the type of
buttons and icons displayed in the pop-up window.
Note For more information about this method, see the WSH documentation.
UserName
If you want the script to output the name of the user that is logging on, you can
use the UserName property of the WScript.Network object to display the
user’s logon name. This personalizes the messages to the user, as the following
example shows:
Example oNetwork = CreateObject("WScript.Network")
WScript.Echo "Welcome " & oNetwork.UserName
Module 6: Creating Logon Scripts 15
Strings Returned
InputBox
sName=InputBox("Enter
sName=InputBox("Enter your
your name")
name")
MsgBox
As well as specify the buttons displayed in a message box, the MsgBox
function returns a value to your script, indicating which button the user clicks.
Because there are several different buttons available, each button returns a
different number in the range 1 through 7. The following table documents the
return values of the MsgBox function.
Button Value Intrinsic constant
OK 1 vbOK
Cancel 2 vbCancel
Abort 3 vbAbort
Retry 4 vbRetry
Ignore 5 vbIgnore
Yes 6 vbYes
No 7 vbNo
16 Module 6: Creating Logon Scripts
The following example displays a message asking the user if he or she has
logged on by using Remote Access Service (RAS). When the user clicks a
button, the corresponding value is stored in the variable vMyVal. If vMyVal is
6, the user clicked the Yes button. As a result, the first message is displayed. If
vMyVal is not 6, the second message is displayed:
Example vMyVal = MsgBox ("Logging on using RAS?", vbYesNo)
If vMyVal = 6 Then
WScript.echo "User Logging in Remotely"
Else
WScript.Echo "User Logging in on LAN"
End If
Note that you can use the intrinsic constant vbYes in place of the literal
number 6.
PopUp
The PopUp method of the WSHShell object can also collect user feedback in a
manner similar to the MsgBox function. The message box types, buttons, and
return values are identical to the MsgBox function. However, as previously
mentioned, you can configure this method to time out if no input is
forthcoming.
If the PopUp method times out before the user clicks a button, it returns a value
of -1. You must always check for this value in addition to the values that are
returned by the user when he or she clicks a button.
Strings Returned
The InputBox function can return a text string typed by the user to your script.
If this function is employed, error handling should be used to ensure that
appropriate input is received from the user.
Input Box
This function has the following syntax:
Syntax InputBox(prompt[, title][, default][, xpos][, ypos][,
helpfile, context])
The prompt and title arguments provide the message box text and title bar text,
respectively, similar to the MsgBox and PopUp functions. The default
argument specifies a default text value for the input box.
InputBox also gives you a high level of control over the position of the
message box on the screen through the xpos and ypos arguments. The helpfile
argument enables you to access a help file if you press the F1 key while the
message box is displayed. The context argument specifies which page of the
help file should be displayed.
Module 6: Creating Logon Scripts 17
In this example, the first line prompts the user for his or her first name and
assigns the answer to the variable vFirstName. The second line prompts for his
or her last name and assigns it to the variable vLastName. These values are
concatenated and stored in the variable vFullName, which is then echoed to the
screen.
18 Module 6: Creating Logon Scripts
Set
Set oIntraLnk=oShell.CreateShortcut("Path\Intranet.URL")
oIntraLnk=oShell.CreateShortcut("Path\Intranet.URL")
oIntraLnk.TargetPath
oIntraLnk.TargetPath == "http://Intra.nwtraders.msft"
"http://Intra.nwtraders.msft"
oIntraLnk.Save
oIntraLnk.Save
Note The “Programs” special folder references the Programs folder on the
Start menu, not the Program Files folder.
Module 6: Creating Logon Scripts 19
Mapping Drives
Topic Objective
To explain how to map The WScript.Network Object
network drives. Set
Set oNetwork
oNetwork == WScript.CreateObject("WScript.Network")
WScript.CreateObject("WScript.Network")
Lead-in oNetwork.MapNetworkDrive
oNetwork.MapNetworkDrive "H:",
"H:", "\\MyServer\Share"
"\\MyServer\Share"
As well as creating desktop
shortcuts, you can map Providing Alternate Credentials
network drives in your logon
scripts. oNetwork.MapNetworkDrive
oNetwork.MapNetworkDrive __
"H:",
"H:", "\\MyServer\Share",
"\\MyServer\Share", ,, “Alan",
“Alan", "PassW"
"PassW"
Removing a Mapping
oNetwork.RemoveNetworkDrive
oNetwork.RemoveNetworkDrive "H:"
"H:"
In the previous syntax, strLocalName is the new drive letter that you want to
map, strRemoteName is the share to map that you want to map to,
bUpdateProfile is an optional Boolean value that indicates whether to save the
new mapping in the user profile (the default is false), strUser is an optional
alternative user identifier, and strPassword is the optional password for the
alternative user.
The following example maps the H drive to a shared folder:
Example Set oNetwork = WScript.CreateObject("WScript.Network")
ONetwork.MapNetworkDrive "H:", "\\MyServer\Share"
Note that the security credentials in this example are those of the user running
the script.
Module 6: Creating Logon Scripts 21
Removing a Mapping
To remove a mapping, you can use the RemoveNetworkDrive method of the
Network object. You must pass the drive letter as an argument. The following
example removes the mapping for the H drive:
Example Set oNetwork = WScript.CreateObject("WScript.Network")
oNetwork.RemoveNetworkDrive "H:"
The second method uses the FileSystemObject object from the Windows
Script Runtime to view all the systems drives. This method is advantageous,
because it returns information about local drives and network drive.
Example Set oFS = CreateObject("Scripting.FileSystemObject")
For Each oDrive in oFS.Drives
sFinalDrive = left(oDrive, 1)
Next
After the last drive letter has been found, the ASC and CHR functions in
Visual Basic Scripting Edition can be used to calculate the next letter in the
alphabet. This is useful when writing a script that maps a new drive while
keeping all existing mappings in place.
22 Module 6: Creating Logon Scripts
Mapping Printers
Topic Objective
To explain how to map a Adding a Printer Connection
network printer.
oNetwork.AddPrinterConnection
oNetwork.AddPrinterConnection "LPT1",
"LPT1", "\\Server\Print1"
"\\Server\Print1"
Lead-in
In the same way that you
oNetwork.AddWindowsPrinterConnection
oNetwork.AddWindowsPrinterConnection "\\Server\Print2"
"\\Server\Print2"
map a network drive, you
can map a network printer.
Removing a Printer Connection
oNetwork.RemovePrinterConnection
oNetwork.RemovePrinterConnection "" Lexmark
Lexmark Optra
Optra SS PS"
PS"
oNetwork.RemovePrinterConnection
oNetwork.RemovePrinterConnection "LPT1:"
"LPT1:"
You can avoid the limitation of only being able to use the number of LPT ports
on the system, by using the AddWindowsPrinterConnection method with
Windows client computers. The syntax for this method is as follows:
Syntax object.AddWindowsPrinterConnection(strPrinterPath,
strDriverName[,strPort])
Sending Keystrokes
oShell.SendKeys
oShell.SendKeys "%fx"
"%fx"
Calling Applications
The following example shows how to run Notepad from a script. As well as
starting Notepad, it also passes the name of the file that you want to open:
Example oShell.Run "%windir%\notepad.exe " & WScript.ScriptFullName
Sending Keystrokes
You can send keystrokes to another program by first calling the AppActivate
method and then calling the SendKeys method of the WScript.Shell object.
The effect of this is like a user entering keystrokes manually. With this method,
you can run menu items and shortcut keys, such as %fx, which is like a user
pressing ALT + F and then X. This closes the program through the File menu.
A complete listing of various control keys is included here for reference.
Key Code
(continued)
Key Code
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}
To specify keys combined with any combination of the SHIFT, CTRL, or ALT
keys, precede the key code with one or more of the following codes.
Key Code
SHIFT +
CTRL ^
ALT %
Caution While using the SendKeys method can be very useful, it is important
to understand its limitations. It is easy for a user to change the focus of a
window while the script is running. This causes the script to fail. SendKeys is
not a robust method and should be used when there is no other way to control
an application.
28 Module 6: Creating Logon Scripts
Objectives
After completing this lab, you will be able to create a logon script that performs
administration tasks such as mapping drives and printers and creating desktop
shortcuts.
Scenario
In this lab, you will write a logon script that maps drives and printers. In
addition, it will create a desktop shortcut to a text file.
After you create and test the script, you will assign it to a user. You will then
test that it runs as expected during the logon process.
Exercise 1
Mapping Drives and Printers
In this exercise, you will create logon scripts that map drives and printers for
the users in the Northwind Traders domain.
To map drives
1. Type the following lines of code to force variable declaration and declare
variables that will be used in this script:
Option Explicit
On Error Resume Next
Dim oNetwork, oDrives, oFSO, Drive
Dim sFinalDrive, iChar, sNewDrive
4. Type the following lines of code to map the drive letter that is determined
above to a share on the instructor’s computer:
oNetwork.MapNetworkDrive sNewDrive & ":", _
"\\London\LabShare"
30 Module 6: Creating Logon Scripts
To map printers
1. Type the following lines of code to map to a printer:
oNetwork.AddWindowsPrinterConnection "\\London\ClassPrn"
2. Type the following line of code to set the printer as the default printer:
oNetwork.SetDefaultPrinter "\\London\ClassPrn"
Exercise 2
Creating Shortcuts
In this exercise, you will create shortcuts to a text file by using Visual Basic
Scripting Edition.
Exercise 3
Assigning Logon Scripts to a User
In this exercise, you will assign the logon script that you have just created to a
user. You will then test that it runs as expected when the user logs on to the
domain.
To verify that your script runs correctly during the logon process
1. Close all open windows and programs.
2. Log off from Windows.
3. Log on to the NWTraders.msft domain as Adminx (where x is your student
number).
4. Click OK when prompted that the logon script has finished.
5. Verify that you have a shortcut to Readme.txt on your desktop.
6. Double-click My Computer.
7. Verify that the drives have been mapped as expected.
8. On the Start menu, click Settings, and then click Printers.
9. Verify that you have a connection to the printer on the London computer.
You have now successfully created, assigned, and tested a logon script written
in VBScript.
Module 6: Creating Logon Scripts 33
Important If you use Group Policy to deploy your logon/logoff scripts, be sure
that a large number of scripts do not run synchronously. The overall script
execution time can cause an unacceptable delay in the logon time for users.
Always test the scripts to make sure that the execution time is acceptable before
assigning the logon script in the production environment.
For computers, using Group Policy to assign logon scripts requires the
following settings:
Run logon scripts synchronously
This setting directs the system to wait for the logon scripts to end before
starting Windows Explorer. The default is for the scripts and Windows
Explorer to run asynchronously, so that scripts are still running when
Windows Explorer is starting.
Note that this setting takes precedence over the user version of this setting.
Run startup scripts asynchronously
This enables startup scripts to run simultaneously. The default is for each
script to end before the next script runs.
Run startup scripts visible
This processes the startup script written in Visual Basic Scripting Edition as
a visible process, thereby displaying each instruction in the script. By
default, these instructions are hidden.
Run shutdown script visible
This assigns the same setting as “Run startup scripts visible,” but for
shutdown scripts.
Maximum wait time for Group Policy scripts
This setting governs how long the system waits to process startup or
shutdown scripts. If this time-out is reached, script processing is forcibly
stopped, and an error is reported in the system event log.
This setting can be very important, because many scripts require some sort
of user interaction. For example, you may write a startup script to connect to
a domain resource. If the account password changes, a dialog box is
displayed that prompts the user to type the correct password.
36 Module 6: Creating Logon Scripts
However, in a startup script, this dialog box will not be displayed, because
the startup script is not interactive. As a result, the system appears to be
hung. In this situation, the “Maximum wait time for Group Policy scripts”
setting governs how long the machine stays in this state before the script is
forcibly stopped. By default, the system waits for 600 seconds (ten
minutes).
Module 6: Creating Logon Scripts 37
Securing WSH
Topic Objective
To introduce WSH security.
Lead-in
VBScript is a powerful
VBScript-Based Viruses
language. Let’s look at ways Remove WSH
that you can secure the
WSH environment. Change default action on .vbs .vbe .js .jse .wsf
Restrict Access to Host
NTFS file system permissions
CScript.exe and WScript.exe
VBScript-Based Viruses
VBScript-based viruses show that creators of viruses can use script. You can
take several steps to minimize the risk of these viruses using the WSH
environment.
One way is to remove the WSH environment. Another way to prevent script
viruses is to change the default application handler for script files.
The following procedure changes the application that opens vbs, .vbe, .js, .jse,
or .wsf files. If those files open, it opens with Notepad.exe and not with the
application handler.
1. Double-click My Computer.
2. On the Tools menu, click Folder Options.
3. Click the File Types tab, and then scroll down to the first item in the list
above .jse, which is a Microsoft JScript® encoded file.
4. Click the .jse file, and then click Edit.
5. In the Action window, click Open, and then click Edit.
6. Change the following line from:
C:\WINNT\System32\WScript.exe "%1" %*
To:
C:\WINNT\System32\Notepad.exe "%1" %*
Repeat these steps for each of the other file types listed previously.
Note Many administrators and users reconfigure the default method of files
with a .vbs or .js extension on their systems so that they open rather than run
when invoked. This is an effective counter-measure that you can use to prevent
the spread of script viruses.
On systems with this configuration, startup and shutdown scripts run correctly.
Logon and logoff scripts fail, because they use the default method. As a result,
instead of having the logon script run, users see the script in an editor (such as
Notepad) when the user logs on and logs off. Users can work around this by
calling the login script directly from within a batch file.
Script Encoder
The Script Encoder (Screnc.exe) is a command-line tool that protects the
contents of a script from unauthorized viewing, copying, or modification, while
still enabling the script to run. The script file is passed to the Script Encoder,
which then performs an encoding routine against the file and creates a new file
with a .vbe (or .jse for Jscript) extension.
This file, if viewed in a text editor, contains what appear to be random
command characters. Changing any part of the file renders it inoperable. This
ensures the integrity of the encoded script, while enabling it to be decoded and
executed by WSH.
Important This encoding only protects the script from a casual attempt at
viewing and modifying script. It does not protect the script from a determined
attempt to crack the encoding mechanism.
The Script Encoder is available from the Microsoft Script Web site at:
http://msdn.microsoft.com/scripting/default.htm?/scripting/vbscript/download/v
bsdown.htm
It is important to note that this script encoder was written primarily for the
encoding of Web-based scripts such as Active Server Pages (ASP). As a result,
many of the switches and examples given as part of the documentation should
not be used for encoding WSH files.
Module 6: Creating Logon Scripts 41
/? Help.
/s Silent. Display no messages.
source The file to encode. It can include wildcard
characters.
destination The destination file.
Note This is a simplified list of the syntax for Screnc.exe. It shows the
switches that are important to the encoding of standard WSH files. For a more
detailed explanation of all of the switches, see the Script Encoder
documentation.
Examples
The following are some examples of how the Script Encoder can be used:
Example screnc Demo.vbs EncodedDemo.vbe
Setting Time-Outs
Setting time-outs can help prevent a hung script from degrading the logon
experience for users.
Setting the script time-out can be achieved by changing either the settings for
the script host or the setting in a .wsh file. However, you can also set a time-out
by using the Script Parameters option when the startup/shutdown or
logon/logoff scripts are assigned in Group Policy. This setting accepts any of
the standard command-line switches for the script engines. For example, the
following switch sets the maximum run-time for the script to 30 seconds:
Example //T:30
Network Bandwidth
There are two areas to consider when using scripts over a network:
Server bottlenecks
Bottlenecks may be the result of multiple simultaneous logon attempts at
peak times. Domain controllers are responsible for authenticating users and
accepting incoming connections from the client computers to retrieve
computer startup scripts and user logon scripts. Servicing all of these
requests may have a negative impact upon the performance of domain
controllers.
Connectivity bottlenecks
The speed of physical links, such as Wide Area Network (WAN) links for
remote sites or RAS links for mobile users, is a factor when assigning
scripts to users and computers. Before any of the scripts run, they must be
copied over the link to the local computer. This can significantly increase
the time it takes for a script to run.
44 Module 6: Creating Logon Scripts
Best Practices
Topic Objective
To introduce best practices.
Lead-in
When working with script,
Test All Changes to Production Logon Scripts
follow these practices. Implement Error Handling
Document Scripts
Be Aware of Network Bandwidth Issues
Protect Scripts with Encoding
Create a “Script Fix” and “Test User” Logon
Document Scripts
Comments help scriptwriters and administrators to understand a script written
by someone else, or even a script that they wrote themselves a few months
previously. Comments make maintaining scripts easier.
Objectives
After completing this lab, you will be able to understand the script time
windows available in Windows 2000 and how you can use them to run script.
Scenario
You are the administrator for the Northwind Traders domain. To ensure that all
of the computers and users in your domain have the appropriate settings, you
must write startup, logon, logoff, and shutdown scripts. You want to use Group
Policy settings to achieve this.
Exercise 1
Configuring Scripts with Group Policies
In this exercise, you will write scripts and manage them by using Group Policy
settings.
• Logoff.vbs
MsgBox "Logging off!"
• Shutdown.vbs
MsgBox "Shutting Down!"
9. Close PrimalSCRIPT.
You have now successfully written scripts that run in the script time windows
that are provided by Windows 2000.
Module 6: Creating Logon Scripts 51
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. Verifying the WSH Environment
Lead-in Common Logon Script Tasks
The review questions cover
some of the key concepts Managing Logon Scripts
taught in this module.
Troubleshooting Logon Scripts
3. What are the four script time-windows that are provided by Windows 2000?
System Startup, User Logon, User Logoff, and System Shutdown.
Contents
Overview 1
Script Arguments 2
Working with Event Logs 3
Generating E-Mail Messages 5
Lab 7.1: Administrative Scripts 7
Managing the Registry 11
Working with Drives, Folders, and Files 13
Setting Folder-Level and File-Level
Security 22
Scheduling Scripts 25
Lab 7.2: Working with the
FileSystemObject 28
Review 32
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 7: Administrative Scripts iii
Instructor Notes
Presentation: This module provides students with the knowledge to script commonly
60 Minutes encountered administrative tasks.
Lab: After completing this module, students will be able to:
60 Minutes
Manage arguments in scripts.
Add entries to Microsoft® Windows® 2000 event logs.
Use Collaborative Data Objects (CDO) to generate e-mail messages.
Use script to manage the registry.
Work with drives, folders, and files by using script.
Schedule scripts.
Required Materials
To teach this module, you need the following materials:
Microsoft PowerPoint® file 2433A_07.ppt.
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
iv Module 7: Administrative Scripts
Module Strategy
Use the following strategies to present this module:
Script Arguments
Make the students aware that they can write scripts that accept arguments at
run time. Emphasize that this approach allows them to write more generic
scripts that can be controlled by passing appropriate arguments as needed.
Make sure that the students understand that dragging files onto a script
causes the file name of that file to pass as an argument to the script.
Working with Event Logs
Explain the importance of being able to log entries in the Windows 2000
Application Event Log.
Emphasize that the source object for any log entries generated by script, in
the manner described in this section, will be Microsoft Windows Script Host
(WSH) and not the script itself.
Because the students are likely to be very interested in this section, ensure
that they all understand how to create different types of log entries, as
described in this section.
Generating E-Mail Messages
Again, the students are likely to be interested in how to send e-mail
messages by using scripts. Explain how easily this can be achieved.
Managing the Registry
Most administrators will want to know how to manipulate the registry by
using script. Describe how this can be easily achieved, but emphasize that
care must be taken when deleting or modifying registry values and keys.
Working with Drives, Folders, and Files
This section recaps how to use the FileSystemObject to manipulate files,
folders, and drives. Provide further details about how to work with these
objects. Do not skim through these topics simply because they have been
mentioned before.
Setting Folder-Level and File-Level Security
This section recaps the Active Directory Services Interface (ADSI) security.
Do not spend too much time on this subject, but instead, refer the students to
scripting security documentation.
Scheduling Scripts
Most students will be familiar with using the Windows 2000 AT Scheduler.
Use this single-slide section to ensure that all students are comfortable with
the process of using the AT Scheduler
Best Practices
This single-slide section simply outlines some good practices. Go through
each recommendation with the students to ensure that they understand all of
the issues in this section.
Module 7: Administrative Scripts v
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Microsoft
Official Curriculum (MOC) courseware.
Important The labs in this module are also dependent on the classroom
configuration that is specified in the section “Customization Information” at the
end of the Classroom Setup Guide for course 2433A, Microsoft® Visual Basic®
Scripting Edition and Microsoft Windows® Script Host Essentials.
Lab Setup
There are no lab setup requirements that affect replication or customization.
This page intentionally left blank.
Module 7: Administrative Scripts 1
Overview
Topic Objective
To provide an overview of
the module topics and Script Arguments
objectives.
Lead-in Working with Event Logs
In this module, you will learn Generating E-Mail Messages
how to use script to perform
common administrative Managing the Registry
tasks.
Working with Drives, Folders, and Files
Setting Folder-Level and File-Level Security
Scheduling Scripts
Script Arguments
Topic Objective
To explain how to send
arguments to a script.
Lead-in WScript Object
You can modify the tasks Arguments Collection
that an administrative script
performs each time it runs
by sending arguments to the For
For ii == 00 to
to WScript.Arguments.Count
WScript.Arguments.Count –– 11
MsgBox
MsgBox "Argument
"Argument "" && i+1
i+1 && "" is
is "" && WScript.Arguments.Item(i)
script. WScript.Arguments.Item(i)
Next
Next
WScript Object
The WScript object has an Arguments collection that gives your code access to
all of the values that are passed in to the script as arguments. The following
script example shows how you can loop through the Arguments collection and
process each argument individually:
Example For i = 0 to WScript.Arguments.Count – 1
MsgBox "Argument " & i+1 & " is " _
& WScript.Arguments.Item(i)
Next
When you invoke a script, you can provide multiple arguments by separating
them with spaces. If you need to pass in values that themselves contain spaces,
you can enclose the values in double quotes (“ ”). The following is an example
of a command line that provides two arguments to a script. Note that one of the
arguments contains spaces:
Example Cscript.exe Args.vbs [email protected] “Kathie Flood”
The intType argument is an integer value that represents the type of event to
log.
You can choose from the integer values in the following table.
IntType Value Meaning
0 SUCCESS
1 ERROR
2 WARNING
4 INFORMATION
8 AUDIT_SUCCESS
16 AUDIT_FAILURE
Note that “strMessage” is the text entry of the event, and “strTarget” is the
target system where the event should be logged. The default target is the local
system.
If the script is run on a Microsoft Windows 95 or a Microsoft Windows 98
machine, the events are logged in a text file called WSH.log in the Windows
folder.
4 Module 7: Administrative Scripts
Configuration Changes
Inherits either IIS or default identity of Outlook Express
The properties and methods of the Message object are self-explanatory, such as
To (comma separators for multiple addresses), Subject, and From.
AddAttachment is a method that can be called multiple times to add several
attachments to a message.
Configuration Changes
You can also configure many settings, such as language, time zone, proxy, and
connection-timeout values, by using the CDO.Configuration object.
If these settings are not changed, default values are loaded from either
Microsoft Internet Information Services (IIS) or the identity of the default
MAPI profile used by your mail client (such as Microsoft Outlook®). Therefore,
it is advisable to use configuration objects if there is a possibility that the
default configuration settings may be inappropriate. If a local SMTP or NNTP
service is found on the computer, the default submittal method for messages is
through the associated pickup directory.
For more information about configuration, see “Configuring the Message
Object” in the CDO for Windows 2000 Platform SDK.
Module 7: Administrative Scripts 7
Objectives
In this lab, you will use the drag-and-drop operation to pass arguments to a
script. You will also write an entry into the Windows 2000 Application Event
Log.
Scenario
As the administrator responsible for writing scripts, you want to make your
scripts as reusable as possible. One way to achieve this is to allow arguments to
be passed to the scripts when they are run. In this lab, you will learn how to
write scripts that accept arguments.
Exercise 1
Passing Arguments to Scripts
In this exercise, you will create a script that accepts a file name as an argument
and displays a message box that contains the script's full path and file name.
Exercise 2
Writing an Event into the Application Event Log
In this exercise, you will add a new section to the previous script that writes a
new entry into the Windows 2000 Application Event Log to indicate which files
were passed as arguments.
Tip The Source columns will specify WSH for the entry generated by your
script.
4. Click OK.
5. Close Event Viewer.
You have now written a script that accepts arguments and writes entries to the
Windows 2000 Application Event Log.
Module 7: Administrative Scripts 11
oShell.RegWrite
oShell.RegWrite “HKLM\..\Current…”,
“HKLM\..\Current…”, “New
“New value”
value”
oShell.RegDelete
oShell.RegDelete “HKLM\System\Current…”
“HKLM\System\Current…”
This method returns different data types, depending on the key value that is set
in the registry. This may cause problems, but the majority of values returned are
strings, integers, or binaries.
Tip Use the VBScript Join function to read from a value registry entry of
REG_MULTI_SZ.
For more information about the Join function, see the VBScript documentation.
If your script attempts to read a key that does not exist, an error will occur. You
can trap the error by using the On Error Resume Next statement and checking
for an Err.Number value that is not 0 (zero). In this way, you can verify the
existence of a key by attempting to read from it.
12 Module 7: Administrative Scripts
This is demonstrated in the script below, which tests for the existence of a
registry key for Microsoft SQL Server™.
Example Dim oShell, sSQLServ
On Error Resume Next
Set oShell = WScript.CreateObject("WScript.Shell")
sSQLServ = oShell.RegRead( _
"HKLM\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\" _
& "CurrentVersion\CurrentVersion")
If Err.Number = 0 Then
WScript.Echo "SQL Server Version is: " & sSQLServ
Else
WScript.Echo "SQL Server Version not found"
End If
If the last character of the key name is a backslash ( \ ), a new key is created
instead of a value. A third optional string argument tells the function what type
of value to write: REG_SZ (string), REG_DWORD (integer), or
REG_BINARY (binary). If no value type is specified, the decision is made by
analyzing the second argument to see if it is a string or an integer.
Caution Use extreme care when deleting or modifying the registry by using a
script. Modifying or deleting certain values or keys may make the operating
system unstable or even unusable.
Module 7: Administrative Scripts 13
The FileSystemObject
This main object allows creation, copying, deletion, and information retrieval
from folders, files, and drives. You must create this object before any other
objects in the Scripting Object Model can be instantiated or used. You use the
following line of script to create an instance of the FileSystemObject object:
Example Set oFSO = CreateObject(“Scripting.FileSystemObject”)
Drive Access
Disk drives are accessed through the Drives collection property of the
FileSystemObject object or by calling the GetDrive method. The following
example shows how to loop through available drives and display some of the
drive properties. Note the use of the IsReady property to check the availability
of a drive. This is useful when you access removable media such as floppy
disks. Also note the use of the With statement, which enables you to perform a
series of actions on a specified object without having to retype the name of the
object for each action.
Module 7: Administrative Scripts 15
Folder Access
You can access folders by using the GetFolder method of the
FileSystemObject object or by using the RootFolder property of the Drive
object to gain access to the SubFolders collection.
The following example loops through the SubFolders collection of the C drive:
Example Set oDrive = oFS.GetDrive("C")
For Each oFolder In oDrive.RootFolder.SubFolders
WScript.Echo oFolder.name
Next
Because each folder also has the SubFolders collection property, it is possible
to loop through all of the child folders of a particular item.
File Access
You can use the Files collection of the Folder object to access file objects on
the hard drive. File properties, including Name, Path, Size, Type, and so on,
are available to your script. The following example loops through the Files
collection of a folder and displays each file name and type:
Example For Each oFile In oFolder.Files
Wscript.Echo " " & oFile.Name & " " & oFile.Type
Next
16 Module 7: Administrative Scripts
Caution Use caution when using script to manipulate the file system because it
is easy to delete every file and folder from a hard drive when using these
powerful objects and methods. Be sure to test your scripts thoroughly before
releasing them into a production environment.
Module 7: Administrative Scripts 17
Sharing Folders
Using ADSI
LanManServer Object
Creating Folders
To create a folder, call the CreateFolder method of the FileSystemObject
object as shown in the following example:
Example oFS.CreateFolder strFolderName
When you create a folder with this object, the parent of the folder must exist
before the new child folder is created or an error will occur.
Deleting Folders
You can use two methods to delete a folder. One is the DeleteFolder method of
the FileSystemObject object. The syntax for this method is shown in the
following example:
Syntax oFS.DeleteFolder folderSpec [, force]
The first argument “folderSpec,” is the folder name and can include wildcard
characters. The optional second argument, “force,” is a Boolean value that
forces folder deletion, even on read-only folders. The default value of this
argument is false. The DeleteFolder method also deletes any files or subfolders
in the chosen folder.
Alternatively, you can delete a folder by calling the Delete method of the
Folder object itself.
Caution These methods will delete the folders and the files that they contain
completely. The folders and files are not sent to the Recycle Bin.
18 Module 7: Administrative Scripts
Sharing Folders
You cannot share a folder by using the Scripting Runtime library. To do this,
you must use the Microsoft Active Directory™ Service Interface (ADSI)
LanManServer object. For more information about ADSI and the
LanManServer object, see Module 5, “Understanding ADSI.”
Module 7: Administrative Scripts 19
The optional second argument is a Boolean value that indicates whether you
want to overwrite an existing file. The default value for this argument is false.
The optional third argument specifies the type of file to create, either ASCII
(the default in Windows 2000) or UNICODE.
The Skip and SkipLine methods allow data to be skipped if required. The text
string returned by these methods can be displayed, parsed by string functions
(such as Left, Right, and Mid), concatenated with other data, and so on. The
following VBScript example demonstrates how to open a file, and then read the
first line from it:
Example Dim oFso, oFile
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oFile = oFso.OpenTextFile("c:\Users.txt", 1)
ReadTextFileTest = oFso.ReadLine
The filename argument is the path and filename of the file to be opened.
The “iomode” switch allows you to specify whether the file is to be opened as
read-only, write-only, or appended to. You cannot open a file with the intention
of reading some lines and then writing others; you must open the file as read-
only, then close the file, and then reopen it as append or write. The following
table shows the constant values that are use to specify the mode in which the
method opens the file.
OpenTextFile Constants
Constant Value Description
The Create argument allows the method to create a new file if the requested
file does not exist. The value should be set to True if you are creating a new
file or to False if this is not required. The default for this value is False.
Module 7: Administrative Scripts 21
The Format argument enables you to specify that the file should be opened as
ASCII, UNICODE, or as the system default. You do this by using the values
shown in the following table.
Format Constants
Constant Value Description
ADSI
Before you can use this interface to set security permissions, you need COM
extensions to enable ADSI to access NT file system (NTFS) permissions. These
extensions provide a consistent security interface for file permissions, but are
currently only available from the ADSI Resource Kit.
For this reason, each machine that attempts to set permissions by using these
extensions must have them installed, or the script will fail. The process is very
similar to the process of setting permissions on objects in Active Directory. For
more information about setting permissions on objects in Active Directory, see
Module 5, “Understanding ADSI.”
XCACLS
An alternative method of setting security permissions is to use the Extended
Change Access Control List (XCACLS) tool from the Windows 2000 Resource
Kit. Xcacls.exe enables you to set all Microsoft Windows Explorer file-system
security options from the command line.
The following example, from C:\Labfiles\Mod6\Mod6xcaclsdemo.vbs,
achieves the same result as the preceding ADSI example:
Example Set oShell = CreateObject("WScript.shell")
oShell.Run "XCACLS F:\ADSIPerms /G NWTraders\FrankL:R /E
/Y", 2, TRUE
Module 7: Administrative Scripts 23
In this script, an instance of the WScript.Shell object is created, and its Run
method is used to execute the XCACLS command. This command adds the
permission for the user “FrankL” to have read-access to the F:\ADSIPerms
folder. This approach requires much less code than using ADSI.
Parameters
Running XCACLS without any parameters displays the following syntax for
the utility:
Syntax XCACLS filename [/T] [/E] [/C] [/G user:perm;spec] [/R user
[...]][/P user:perm;spec [...]] [/D user [...]] [/Y]
This command allows the use of wildcard characters, multiple users in a single
command, and the combination of multiple access rights.
The following table describes these parameters.
Parameter Description
/G in Detail
The /G switch is the most complex part of the XCACLS utility. It consists of
the following three parameters.
User
This is the name of the account on which the permissions are being set.
Acceptable name formats are:
UserName or DomainName\UserName
GroupName or DomainName\GroupName
24 Module 7: Administrative Scripts
Perm
Perm represents the special file-access-right mask for directories, which applies
permissions to the files. Perm can be one of the following values:
R (Read)
C (Change)
F (Full control)
P (Change Permissions)
O (Take Ownership)
X (Execute)
E (Read)
W (Write)
D (Delete)
Spec
Spec applies settings to folders only. It is possible to set an Access Control
Entry (ACE) for the folder itself without specifying an ACE that is
automatically applied to new files created in that folder. You accomplish this by
using the specifier, T, following the semicolon. All access rights specified
between the semicolon and the T are ignored. At least one access specifier must
follow the T. This means that only an ACE for the folder will be created.
All other options, which can also be set in Windows Explorer, are subsets of the
possible combinations of the basic access rights. Therefore, there are no special
options for directory access rights, such as List or Read.
Spec can be the same as Perm, and is only applied to a directory. In this case,
Perm will be used for file inheritance in this directory.
Examples
Example XCACLS *.* /G administrator:RW /Y
This command replaces the access control list (ACL) of all files and folders
found in the current folder without scanning any subfolders and without
confirmation.
Example XCACLS *.* /G MyUser:RWED;RW /E
This command edits the ACL of a file or a folder, but its effect on a folder is
different. The ACE that is added to the folder is also an inherited ACE for new
files created in this folder. In this example, “MyUser” is granted read, write,
execute, and delete rights for all new files created in this folder, but only read
and write permissions for the folder itself.
Example XCACLS *.* /G MyUser:R;TRW /E
This command grants read and write permissions for a folder without creating
an inherit entry for new files. Therefore, in the previous example, new files
created in this folder do not get an ACE for MyUser.
Module 7: Administrative Scripts 25
Scheduling Scripts
Topic Objective
To introduce the
Windows 2000 Scheduler.
Lead-in The AT Scheduler
You can schedule scripts to Scheduling Service
be executed at appropriate
times. Scheduled Task Wizard
Error Log if Task Fails
SchedLog.txt
The AT Scheduler
The AT command line utility for scheduling, or AT Scheduler, is available in
all Windows 2000 operating systems. You can use this utility to schedule the
running of scripts from the command line.
In Windows 2000, you will see tasks created by the AT command in the
Scheduled Tasks folder of the Control Panel.
Scheduling Service
The Scheduled Tasks folder in the Control Panel contains a wizard that helps
you to add any application or script file to a schedule. The schedule can be set
for daily, weekly, monthly, and other frequencies, and requires a user name and
a password with sufficient security permissions to run the program or execute
the script. In addition to these basic features, you can set advanced properties to
control the schedule, including the ability to run the application or script only
when the machine is in an idle state.
Tip Scheduled tasks are stored as .job files in the Windows\Tasks folder.
Because these tasks can be copied in the same way as any file, you can create
your job on one machine, and then copy the file as part of a logon script to
make distribution easier.
Module 7: Administrative Scripts 27
Best Practices
Topic Objective
To explain good practices
for using administrative
scripts. Build Error Handling into the Scripts
Lead-in Test All Administrative Scripts Extensively
The following are some best
practices for working with Be Careful When Using the FileSystemObject for
administrative scripts. Deletions
Back Up the Registry Before Testing Scripts
Objectives
After completing this lab, you will be able to use the FileSystemObject to
create and write to files, and extract information about the folders on each of the
drives on your computer.
Scenario
As an administrator, you often need to audit the contents of your users’
computers. This can be a time-consuming and tedious task. You have decided
that scripting the audit and recording the contents of the computer drives in a
text file would suit your needs. In this lab, you will write a script that
documents all of the folders on all of the drives of a computer. It will record the
details in a text file.
Exercise 1
Documenting your Computer Drives and Folders
In this exercise, you will use the FileSystemObject to create and write to a file
that contains information about the folders and hard drives on your computer.
5. Write the GetDriveString function at the end of the script by typing the
following code:
Function GetDriveString(iDriveType)
Const CDRom = 4
Const Fixed = 2
Const RamDisk = 5
Const Remote = 3
Const Removable = 1
Const Unknown = 0
Const CDRomString = "CDROM"
Const FixedString = "Fixed"
Const RamDiskString = "RamDisk"
Const RemoteString = "Remote"
Const RemovableString = "Removable"
Const UnknownString = "Unknown"
Select Case iDriveType
Case CDROM
GetDriveString = CDRomString
Case Fixed
GetDriveString = FixedString
Case RamDisk
GetDriveString = RamDiskString
Case Remote
GetDriveString = RemoteString
Case Removable
GetDriveString = RemovableString
Case Else
GetDriveString = UnknownString
End Select
End Function
6. Write the WriteFolder subprocedure at the end of the script by typing the
following code:
Sub WriteFolder(ByRef oFol, ByVal sSpaces)
Dim oFolder
On Error Resume Next
For Each oFolder in oFol.SubFolders
sOutPut = sSpaces & "-" & oFolder.Name
If Err.Number = 0 Then oFileTS.WriteLine sOutput
Err.Clear
WriteFolder oFolder, sSpaces & " "
Next
End Sub
Note The script may take a few seconds to run because it retrieves
information about all of the folders on all of your drives.
Review
Topic Objective
To reinforce module
objectives by reviewing key Script Arguments
points.
Lead-in Working with Event Logs
The review questions cover Generating E-Mail Messages
some of the key concepts
taught in the module. Managing the Registry
Working with Drives, Folders, and Files
Setting Folder-Level and File-Level Security
Scheduling Scripts
Contents
Overview 1
Windows Script Files 2
Using COM Components 7
WMI 9
Scripting Microsoft Office 13
ASP Pages 18
Review 21
Information in this document, including URL and other Internet Web site references, is subject to
change without notice and is provided for informational purposes only. Unless otherwise noted,
the example companies, organizations, products, domain names, email addresses, logos, people,
places and events depicted herein are fictitious, and no association with any real company,
organization, product, domain name, email address, logo, person, places or events is intended or
should be inferred. Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 8: Beyond the Basics iii
Instructor Notes
Presentation: This module provides students with an introduction to various tasks that they
60 Minutes can achieve with Microsoft® Visual Basic® Scripting Edition.
After completing this module, students will be able to:
Describe Microsoft Windows® script (.wsf) files.
Describe how Component Object Model (COM) components can enhance
the power of scripts.
Describe Windows Management Instrumentation (WMI).
Begin scripting applications in Microsoft Office.
Describe Active Server Pages (ASP).
Find more information about scripting.
Required Materials
To teach this module, you need the following materials:
• Microsoft PowerPoint® file 2433A_08.ppt
Preparation Tasks
To prepare for this module, you should:
• Read all of the materials for this module.
iv Module 8: Beyond the Basics
Module Strategy
Use the following strategy to present this module:
Windows Script Files
Use this section to introduce Windows script files. Explain the advantages
and features that Windows script files add to the students’ scripts.
Using COM Components
The students have already used COM components, such as Microsoft Office
and Microsoft ActiveX® Data Objects (ADO), in the course. Use this
section as a recap, and use it to provide further references.
WMI
Use this section to introduce WMI. Explain the advantages and features that
WMI adds to the student's scripts.
Scripting Microsoft Office
The students have already used Microsoft Office objects in this course. Use
this section as a recap, and use it to provide further references.
ASP Pages
Provide a very brief introduction to ASP pages, and point out its advantages.
Use this section to provide further references for ASP pages.
Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Training and
Certification courseware.
There are no labs in this module, and as a result, there are no lab setup
requirements or configuration changes that affect replication or customization.
Module 8: Beyond the Basics 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Windows Script Files
Lead-in Using COM Components
In this module, you will learn
about how to further apply WMI
script and where you can
find out more about these Scripting Microsoft Office
topics.
ASP Pages
Note Before the release of WSH 2.0, the .ws extension was used for XML
format script files and is still referred to by many reference books.
4 Module 8: Beyond the Basics
You must identify each job by using a unique job identifier. To run that portion
of script, you can then reference these identifiers by using a command similar to
the following:
In this example, JobName is the name, or identifier, of the job contained in the
Allmyscripts.wsf file.
A .wsf file encapsulates a library of functions that multiple .wsf files can use.
The following example shows the contents of a .wsf file that includes a JScript
file (fso.js). It also includes a VBScript function that calls the GetFreeSpace
function in the included file, as follows:
Example <Job id="IncludeExample">
<script language="JScript" src="FSO.JS"/>
<script language="VBScript"> ' Get the free space for drive C.
s = GetFreeSpace("c:")
WScript.Echo s
</Script>
</Job>
Note You have already used COM components in this course, such as the
Connection, Command, and Recordset ADO objects.
Module 8: Beyond the Basics 9
WMI
Topic Objective
To introduce this section.
Lead-in
Windows Management
WMI Architecture
Instrumentation (WMI) Practice: Using WMI
interfaces increase the
functionality of your
administrative scripts.
WMI Architecture
Topic Objective
To introduce the WMI Script
architecture. WMI
Lead-in CIM Repository
WMI is made up of several Static Info. Sources Common Information Model
components. CIM Schema Object Manager
(CIMOM)
WMI Providers
SNMP PerfMon ADSI Registry Event Log Win32
WMI providers
WMI providers are COM objects that are interpreters for WMI. They enable
WMI to communicate with specific objects in a manageable and scalable
manner. Providers available as part of Microsoft Windows 2000 include:
• Win32.
• Registry.
• ADSI (Active Directory Services Interface).
• Event Viewer logs.
• Performance Monitor (PerfMon).
• Simple Network Management Protocol (SNMP).
This opens a new instance of Excel, which is not visible by default. You can
make the Excel instance visible by setting the Visible property of the
Application object.
Module 8: Beyond the Basics 15
After you create the Application object, you use the Workbooks collection to
perform tasks such as opening a file or creating a new file. Collections contain
one or more objects of the same type, in this case, the Workbook objects. An
example of how to open a Workbook object and store a reference, or variable,
to it is shown below:
Example Set oWorkbook = oExcelApp.Workbooks.Open(“C:\Users.xls”)
Most of the work that you want to do with Microsoft Excel can be done with
Worksheet objects. This type of object gives you access to other objects, such
as Ranges. There are various ways to navigate to a Worksheet object. The
simplest approach is to specify the ordinal number or the name of the
Worksheet object that you require in the Workbook object’s Worksheets
collection.
It is also useful to automate Excel for logging or reporting purposes. You can
use the Cells property to write and read information.
You can also chart data by using the Chart object. You create a chart by using
the Add method of the Workbook object’s Charts collection.
The easiest way to create a chart is to programmatically select the data that you
want to chart, and then use the following method:
Example Set oChart = oWorkbook.Charts.Add
The following script manipulates the most commonly used Excel objects. The
script:
Creates an Application object.
Creates a new Workbook object
Populates a Worksheet with data.
Selects the data.
Creates a chart.
Manipulates the chart.
Saves the Workbook object.
Quits Microsoft Excel.
16 Module 8: Beyond the Basics
ASP Pages
Topic Objective
To introduce this section.
Lead-in
Active Server Pages are the
Introduction to ASP Pages
foundation for many Web Practice: Using ASP
applications.
Interactive Script
ASP pages combine the power of Visual Basic Scripting Edition with the
display and interactivity of HTML. ASP pages are a simple platform on which
you can develop rich and powerful Web applications. You can build intuitive
administrative interfaces for Windows 2000 by using ASP pages.
ASP is a large subject that is beyond the scope of this course. However, if you
start programming with ASP pages, you will find that many of the concepts
involved are easy for you to understand, because you use VBScript in ASP
pages to achieve your goals.
20 Module 8: Beyond the Basics
Note This demonstration is a slightly modified version of the DS Info Web site
from the Microsoft Press book, “Building Enterprise Active Directory™
Services: Notes from the Field.”
Module 8: Beyond the Basics 21
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. Windows Script Files
Lead-in Using COM Components
The review questions cover
some of the key concepts WMI
taught in the module.
Scripting Microsoft Office
ASP Pages
3. What is the name of the highest-level object that must be used to control
Microsoft Excel in your scripts?
Application.
4. Does ASP code run on the Web browser or on the Web server?
On the Web server.
THIS PAGE INTENTIONALLY LEFT BLANK