0% found this document useful (0 votes)
709 views

Introduction To VBScript

This document introduces VBScript and provides an overview of the topics that will be covered. It discusses the benefits of learning VBScript for automating network administration tasks. It also provides some tips for writing scripts, including using comments, testing versions of scripts, and mimicking tasks that can be done manually. The first section provides a simple script to check the version of VBScript being used.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
709 views

Introduction To VBScript

This document introduces VBScript and provides an overview of the topics that will be covered. It discusses the benefits of learning VBScript for automating network administration tasks. It also provides some tips for writing scripts, including using comments, testing versions of scripts, and mimicking tasks that can be done manually. The first section provides a simple script to check the version of VBScript being used.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Introduction to VBScript.

doc By Guy Thomas

Introduction to VBScript by Guy Thomas


September 2005

Table of Contents

Introduction to VBScript - Home by Guy Thomas ........................................... 2


Section 0 Introduction to VBScript ............................................................... 3
Section 1 VBScript - Check Version ............................................................. 5
Section 2 VBScript - Variables .................................................................... 9
Section 3 Create an OU (Organizational Unit) in Active Directory ....................14
Section 4 Create a User in Active Directory .................................................21
Section 5 Map Network Drive ....................................................................26
Section 6 Map a Network Printer................................................................29
Section 7 Create a Folder (Stage 1 of 3) .....................................................33
Section 8 Create a Text File (Stage 2 of 3) ..................................................37
Section 9 Append Data to Text File (Stage 3 of 3) ........................................41
Section 10 Registry Scripting ....................................................................45
Section 11 WMI Scripting - Memory ...........................................................50
Section 12 WMI Scripting - Chassis Type ....................................................54

Who is this Introduction to VBScript ebook aimed at?


Administrators who need to write simple VBScripts.
Techies wishing to automate repetitive computer tasks.
Scriptwriters who are curious to know the difference between VBScript and
JScript.
Network Mangers who to more control over their servers.

Page 1 of 59
Introduction to VBScript.doc By Guy Thomas

Introduction to VBScript
by Guy Thomas

Simple, yet powerful VBScripts

Introduction to VBScript
I divided my mission into two strands. In the first strand, I will show you the
range of computing tasks that VBScript can automate. While, in the second
strand I will explain the VBScript commands, methods and syntax. To fulfil my
mission, I am going to provide you with scripts, which have a practical purpose,
yet are interspersed with VBScript learning points.

Here are the two parallel strands:

Tasks for VBScript VBScript Methods, Commands &


1. Check Version of VBScript Syntax
' Comments (1,10)
2. Variables and Hungarian
Convention Error Correcting Code (3, 8,11)
If Then.. Else... End If (3, 8, 11)
3. Active Directory - Create OU Input Box (11)
4. Active Directory - Create Loop For...Next (2, 12)
Users On Error Resume Next (1)
Option Explicit (1-12)
5. Map Network Drive Select Case (12)
6. Map Printer and Set Default Split (10)
Printer Sub Routine (2)
WScript.Echo (1-12)
7. Create a Folder Underscore (_) (1)
8. Create a File Variables - Hungarian Convention (2)
VbCr and vbTab (1)
9. Write Text to a File
10. Read and Write to the
Registry
11. WMI - Memory Bind to Active Directory
GetObject("LDAP://RootDSE") (3,4)
12. WMI - Chassis Type .Create("Organizational Unit") .SetInfo
(3)
CreateObject("WScript.Network") (5,6)
CreateObject("WScript.Shell") (7,10)
CreateObject("Scripting.FileSystemObjec
t") (7,8,9)
.CreateFolder .CreateTextFile (7)
.OpenTextFile ForAppending (9)
RegRead RegWrite (10)
MapNetworkDrive (5)
AddPrinterConnection SetDefaultPrinter
(6)
WMI - GetObject("Winmgmts") (11, 12)

Page 2 of 59
Introduction to VBScript.doc By Guy Thomas

Section 0 Introduction to VBScript

Simple, yet powerful VBScripts

Introduction - What are the Benefits of Learning VBscript?


I truly believe that VBScript has a future for automating network administration.
The sheer variety of jobs where a VBscript saves time still amazes me. For
example, to map network drives or printers, to create users in Active Directory,
to read and write from files. In addition, there are whole areas of computing
which are transformed by scripting, WMI and manipulating the registry spring to
mind.

This ebook will give you an appreciation of the range of VBScript objects, for
example, Active Directory, LDAP, Network, Shell and FileSystemObject. We will
also manipulate with scripting methods for instance, looping and if...then...else
logic.

Skills (Multi-Skills)
Surprisingly, the principle skills that you need to be proficient at VBScript are not
mathematical, but logical and linguistic. Attention detail is more important than
genius, especially when you are getting started. My most enduring advice is keep
it simple, build your scripts gradually. Even though my scripts are
straightforward, you need no conceptual jump to switch from these short
examples to a comprehensive real-life script. Can you assemble one table from a
flat-pack? Then you could build a whole office suite, provided you had the time.
It s the same principal with scripting; at the end of this course, you will be expert
at powerful short scripts. It will then be a short step to assembling a series of
simple scripts into a complex production script.

VBScript is a simple yet powerful language with its own rules and syntax. In
VBScript, we have a structured system for creating objects, manipulating their
properties and setting values. Because the VBScript language is so efficient, each
and every word is loaded with meaning.

My not so hidden agenda will be to increase your scripting vocabulary. We can


begin by looking out for specialist uses of common words such as, loop, split and
echo. Let us get into the habit of examining each statement and analyzing the
significance of every word. Here are three examples to illustrate what I mean.

Examples

What is the name of the object created here? Set objShell =


CreateObject("WScript.Shell") (Ans: objShell)
What is the property of objShell called? objShell.SendKeys "Hello Guy" (Ans:
.SendKeys)
How could we change the value from "Hello Guy" to say "Goodbye"?
objShell.SendKeys "Hello Guy"
(Ans: objShell.SendKeys "Goodbye")

Page 3 of 59
Introduction to VBScript.doc By Guy Thomas

One revelation from my post-bag, which constantly amazes me, is the different
ways that people write scripts. Another surprise is that each person thinks that
their way is the only way to write code. Naturally as your mentor, I will give you
ideas, but please distil my advice and devise methods which suit you. Here are a
few secrets learnt at the bitter school of hard knocks.

Secrets of Scripting
Develop a naming convention for all your scripts.
Save your scripts in a special folder.
Don't be afraid to create lots of versions of test scripts. Many is the time
that I end up with a script that does not work and I cannot find out why.
The speediest solution is to revert to a version that I saved earlier which
did work.
Make liberal use of comments, especially at the top of the script. Six
months later, you will forget why made the script.
When scripting Active Directory, create a test OU, a test user.
Always remember that Scripting mimics task that you can carryout
manually with Explorer, Active Directory Users and Computers or even
Regedit.
Get a good scripting editor at the outset, for Example OnScript.

This page covered the following VBScript ideas.

My theme of this ebook is that VBScript provides variety of opportunities to


automate network tasks. To be successful at VBScript while you need to be
multi-skilled, a logical and methodical mind is more important than mathematical
skill.

Page 4 of 59
Introduction to VBScript.doc By Guy Thomas

Section 1 VBScript - Check Version

Which Version of VBScript are you using?

Introduction to Checking Version Numbers


I want to begin with the relatively easy task of checking your VBScript version
numbers. For this first script, I want to concentrate on the pure VBScript
commands, methods and syntax. For example,
WScript.Echo, .Version, underscore (_) and vbCr.

There are occasions when you need to investigate the VBScript version number.
For example, if you have old clients with version 2, some VBScript commands
may not work. To give a specific example, you may want a script to pause, in
which case you could use WScript.Sleep. The problem is that this, .Sleep
property was only added in WSH version 5.1. In fact, we are faced with a
paradox, modern XP machines, which don t really need to pause, obey the .Sleep
command, whereas Windows 9x machines, which need .Sleep, cannot interpret
this command. Thus, our task is to build a very simple script that checks the
version of VBScript.

The first bonus of checking version numbers is that our investigation reveals just
how many components are involved in a VBscript, for instance, Windows Scripting
Host (WSH) and also VBScript itself.

Topics for Checking Version Numbers


Example 1 - VBScript to Check the WSH Version
Example 2 - VBScript to Check the WSH Version and Build Number
Example 3 - VBScript to Check the VBScript Version
Summary of Checking Version Numbers

Example 1 - VBScript to Check the WSH Version


VBScripts need a shell called WSH (Windows Scripting Host). I visualise the WSH
shell as a room where the script engine performs its instructions. My point is that
if there is no WSH room , then VBScript cannot process our instructions.
Examples 1 and 2 are designed to extract the version information about WSH and
'echo' the information to your screen. (In Example 3 we switch to the VBScript
executable itself.)

Prerequisites
This is a script that will execute equally well on a Windows server or an XP
machine.

Instructions for Checking WSH Version

1. Copy and paste the example script below into notepad or a VBScript editor.
2. Save the file with a .vbs extension, for example, WSH.vbs
3. Double click WSH.vbs and read the version in the message box.

Page 5 of 59
Introduction to VBScript.doc By Guy Thomas

Sample VBScript to Check the WSH Version


' WSH.vbs
' Sample VBScript to check WSH Version
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.3 - September 2005
' --------------------------------------------------------------------
On Error Resume Next
WScript.Echo "WSH Version: " & WScript.Version
WScript.Quit

Learning Points
Note 1: WScript.Echo calls for a WSH message box. The
next command "WSH Version: " & WScript.Version, tell
the script engine what to put in that box. I am expecting
the script to return a WSH message box displaying - WSH
Version: 5.6. See screen shot opposite.

WScript.Echo may seem trivial, as it does not actually do any useful work,
however, WScript.Echo is worth mastering, as it is probably the number one
technique in troubleshooting VBScript. Incidentally, this command is not case
sensitive. (Wscript.echo is equally as effective.)

Note 2: Observe that we have a mixture of literals - "WSH Version: " and
variables - WScript.Version. Paying attention to detail pays off. In this instance,
notice how the space before the closing quotes makes the output easier to
understand.

Note 3: Time and time again ampersand (&) is your friend for joining VBScript
components. I have to confess that I am often concentrating so hard on the
more difficult commands that I forget the ampersand. When I make this sin of
omission, WSH brings me up sharply with a message: Code 800A0401 - Expected
end of statement.

Note 4: 'On Error Resume Next' is not strictly necessary in this script. This is
the basic troubleshooting command that says, if there is a problem, carryon and
do your best. In other scripts, On Error Resume Next salvages useful commands
after a mistake, moreover, it suppresses the WSH error message box.

Note 5: I almost forgot to mention ' Comments. A single quote tells VBScript to
disregard what follows the single quote. The first five lines of this script are
remmed out using this technique. The idea is to add explanations of what the
script is designed to achieve. With a long script, I like to add comments between
each section.

Page 6 of 59
Introduction to VBScript.doc By Guy Thomas

Example 2 - VBScript to Check the WSH Version and Build Number


Script to Display WSH and File Information

WSHname.vbs
' Sample VBScript to check WSH Version
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.3 - September 2005
' --------------------------------------------------------------------
On Error Resume Next
WScript.Echo "WSH Version: " & WScript.Version & " " & WScript.BuildVersion _
& vbcr & "File name: " & WScript.ScriptName
WScript.Quit

Learning Points
Note 1: Most of the time, I only use WScript.Echo and perhaps WScript.Quit, I
was surprised to discover that WScript has so many other properties, for example
.Version, .BuildVersion and even .ScriptName. From a teaching perspective, the
message is that objects have properties, which we access with the syntax
object.dot.property. Incidentally, my WScript build number was 8827.

Note 2: One potential problem with VBScript commands is that they run to more
than 80 characters. Moreover, VBScript has no concept of word-wrap, so if you
just continue the same instruction on the next line, VBScript will interpret your
intention as two instructions and not one. Fortunately, there is a solution, the
underscore (_). What underscore does is tell VBScript that the command has not
yet finished, but to read the second half of the same command on the next line.

If you are familiar with other scripting languages then you could looking upon the
(_) is as an escape character for the carriage return.

Note 3: Observe the command vbcr, this makes a carriage return in the actual
output message box. It is purely cosmetic, but it often makes output easier to
understand. Take the time to be sure of the difference between (_) and vbCr.
For instance, remove the (& vbCr) and the script will still run. However, remove
the (_) and it will not work.

Example 3 - VBScript to Check the VBScript Version


As we will see, our scripts require both VBScript itself and also a WSH shell. This
script concentrates on the version number of the VBScript executable.
Incidentally, you can confirm the information by checking the information directly
on cscript.exe and wscript.exe in the Windows\System32 folder.

Please note that this script checks VBScript and is different from Example 1 and 2
which report version numbers for WSH. Specifically, check how the commands
ScriptEngineMajorVersion and ScriptEngineMinorVersion replace WScript.Version.

Page 7 of 59
Introduction to VBScript.doc By Guy Thomas

Sample Script to Check the VBScript Version


' VBScript.vbs
' Sample Script to check VBScript Version
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.1 - September 2005
' --------------------------------------------------------------------
WScript.Echo "VBScript Version: " & ScriptEngineMajorVersion _
& "." & ScriptEngineMinorVersion
WScript.Quit

Learning Points
Note 1: Unlike example 1 this script needs to build the
version number from two numbers, and artificially
concatenate a dot (".") in between the two parts of the
version number.

Challenge:
These three scripts are so short that you could easily bolt them together. This
would mimic real life situations where you build scripts in stages, get them
working and then bolt them together to create the production script.

Summary of Checking Version Numbers


From a practical point of view, it may be necessary to check the version of
VBScript or WSH. From a pure scripting point of view, there are parallels with
English. When composing ordinary English, many of us - me included, are unsure
when to use a semi-colon; a dash is even harder to master. Syntax is equally
important in VBScript, therefore take a minute or two to master the underscore
(_) and vbcr.

This page covered the following VBScript methods, commands and


syntax:

WScript.Echo, vbCr, Underscore (_)

Page 8 of 59
Introduction to VBScript.doc By Guy Thomas

Section 2 VBScript - Variables

Variables are a vital scripting tool

Introduction to VBScript Variables


On this page I am going to take two learning themes and weave them together.
One theme is represented by VBScript variables and the other theme is creating a
computer account.

Later on this page, we will discuss the advantages of using the Hungarian
Convention for naming variables, but first, let us review what the term variable
means in the context of VBScript. One obvious definition of a variable is the
opposite of a constant. Constants remain at their initial value, whereas variables
can change their values during the course of a script, for example, processing a
different account each time the script goes through a loop. Think of variables as
placeholders for items that will change during the course of a script.

In this ebook, we will create three types of Active Directory Objects,


.Create("Computer..."), .Create("Organizational Unit..."), and .Create("user...").
This page features the .Create("Computer..") method, once you have mastered
the VBScript technique for a computer, then you can apply it to different
situations, for example, create an OU (Section 3) or create a User (Section 4).
Even if you don't have Active Directory, you can still study the VBScript methods,
for example, GetObject("LDAP://rootDSE"), .SetInfo and .Put.

Topics for Variables


What is a VBScript Variable?
Example 1 - Using a String Variable
Example 2 - Using a Variable to Increment a Loop
The Hungarian Variable Convention
Summary of VBScript Variables

What is a VBScript Variable?


The discipline of declaring variables gives me control over VBScript. Variables
help me plan and best of all, variables help me when it comes to troubleshooting
scripts. I use variables in two ways, firstly, suppose I want to repeat the name of
one computer again and again throughout the script. What I do is assign a name
to a variable at the start of the script, thereafter I use the variable when I want
to refer to the name. For example strXP = "XPMachine". The payback for what
may seem like extra work, is when I want the script to work with a different
value, say strXP = "VistaMachine". I only have to change the value in one place,
moreover, I know that place will be near the top of my script.

My second job for variables is as placeholders in loops. Incidentally, loops never


cease to amaze me for their power to automate repetitive tasks. Let us imagine
that I have a VBScript routine, which creates a Computer, imagine also that I
have a list of 100 machine names in a file. Loop + variable + incrementor = lots
of new Computer accounts. To keep it simple, on this page the scripts do not
read from a file, instead each loop appends a different number to the base name,
XPMachine1, XPMachine2 etc..

Page 9 of 59
Introduction to VBScript.doc By Guy Thomas

Example 1 - Using a String Variable


In this first Example, observe how VBScript employs the variable strXP to build
the new computer object. See how I set strXP = "XPMachine. Then look again
and see how many more times strXP appears in the script. Now see how easy it
would be to change strXP to = "VistaMachine", compared with the hassle of
changing each of the two, or is it three, further occurrences of the corresponding
computer name.

Prerequisites

While I designed this script purely to demonstrate variables, there is no reason


why you should not create and test the following VBScript provided you are
connected to an Active Directory Domain.

Instructions

1. Copy and paste the script below into notepad.


2. Save the file with .vbs extension e.g. ComputerSimple.vbs
3. Double click and then check the message box
4. You may like to launch Active Directory Users and Computers and check
the Computers container for new Computer accounts. Press F5, or refresh
as necessary.

' ComputerSimple.vbs
' Sample VBScript to create a Computer (Simple)
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.2 - September 2005
' ----------------------------------------------------------------
Option Explicit
Dim strXP, objRootDSE, objContainer, objComputer
strXP = "XPMachine"
Set objRootDSE = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://cn=Computers," & _
objRootDSE.Get("defaultNamingContext"))

Set objComputer = objContainer.Create("Computer", "cn=" & strXP)


objComputer.Put "sAMAccountName", strXP & "$"
objComputer.Put "userAccountControl", 4096
objComputer.SetInfo
WScript.Echo "Created a new computer called " & strXP
WScript.Quit

Learning Points
Note 1: For now, trust me, just concentrate on the variable strXP and do not
worry about how the script binds to Active Directory. (We will cover Active
Directory components in section 3.)

Note 2: By declaring and using variables in your VBScripts, you can manipulate
their values later in the script. Trace all the occurrences of strXP in the above
example.

Note 3: Incidentally, VBScript reserves a place in memory for each variable.

Page 10 of 59
Introduction to VBScript.doc By Guy Thomas

Example 2 - Using a Variable to Increment a Loop.


Loop counters are another classic application for variables. See how the script
creates 10 computers and puts them all in same OU. The variable
intComputerNum is a vital cog in enabling the script loop ten times. The result is
an efficient script, which builds computers accounts. Thanks to the variable
intComputerNum, the machines have unique names, XPMachine1 to
XPMachine10.

' ComputerLots.vbs
' Sample VBScript to create 10 Computers
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.3 - September 2005
' ----------------------------------------------------------------
Option Explicit
Dim strXP, objRootDSE, objContainer, objComputer
Dim intComputerNum, objNew
strXP = "XPMachine"

Set objRootDSE = GetObject("LDAP://rootDSE")


Set objContainer = GetObject("LDAP://cn=Computers," & _
objRootDSE.Get("defaultNamingContext"))

For intComputerNum = 1 To 10
objNew = strXP & intComputerNum
Set objComputer = objContainer.Create("Computer", "cn=" & objNew)
objComputer.Put "sAMAccountName", objNew & "$"
objComputer.Put "userAccountControl", 4096
objComputer.SetInfo
Next
intComputerNum = intComputerNum -1
WScript.Echo intComputerNum & " new computers created "

Note 1: In Example 2 (above), I would like to isolate the For... Next loop and
concentrate on the role of the variable intComputerNum. So often, the real
reason why you are creating a script is to automate a repetitive task. That
means getting the basic task correct, (Example 1) and then 'topping and tailing'
the script with a For ... Next loop. (Example 2).

Note 2: The command: For intComputerNum = 1 To 10 controls how many


loops, how many computers to create. While I used a long variable name
intComputerNum, many scriptwriters would have used, For i = 1 to 10. The
reason that I choose a long name is because 'i' is such a short variable name, if
you blink, you miss the fact that the command is using a variable.

Note 3: From an Active Directory perspective, this script demonstrates that you
need to create a sAMAccountName for a computer object. It also shows that the
default UserAccountControl value for a computer is 4096 and not 512. I say
again, we will feature the Active Directory commands in later scripts (page 3).

Page 11 of 59
Introduction to VBScript.doc By Guy Thomas

The Hungarian Variable Convention


The idea behind the Hungarian naming Convention is to give variables consistent
and meaningful names, especially with the prefix part of the variables. VBScript
allows to you declare variables beginning with any reasonable alphanumeric
character. The Hungarian Convention says, 'Wouldn't it be a good idea to always
begin string variables with s (or str) and integers with i (or int)'. At a stroke, the
prefix gives you an extra clue about the purpose of the variable. For example,
strContainer expects a string value such as "XPMachine"; whereas a variable
called intCounter, intimates that the values will be whole numbers.

VBScript does not insist upon the Hungarian Convention. On the one hand, I
wish VBScript would enforce strict naming; on the other hand it allows you, or I,
to develop our own dialect of the Hungarian Convention. One of the stricter
dialects of the Hungarian Convention uses mainly single letter prefixes, for
example, s for string, o for object, i for integer.

My message is this, devise your own dialect of the Hungarian Convention and
stick to it. If you would like to research the Hungarian Convention, look for the
names Charles Simonyi, who invented the convention and Charles Petzold who
adapted it to Windows scripting. To summarise, naming variables consistently is
important, the Hungarian Convention is a worthy concept. Incidentally, other
scripting languages enforce the convention more rigorously than VBScript.

Here is a system that I try to adhere to:

int - Integer. Example intComputerNum representing 10 or 50


str - String. Example strOU or strDomain
obj - Object. Example objUser or objComputer

There are other less common variable prefixes, for instance: err - error, dtm -
date, boo - Boolean. Are variables case sensitive? The answer is no. For
instance, strXP would be the same as StrXP or strXp. That does not mean that
you should change capitalization from one instance to the next. Get into good
habits; they will reward you when it comes to dealing with Active Directory
properties which are case sensitive.

Page 12 of 59
Introduction to VBScript.doc By Guy Thomas

Hungarian Convention Example:


Let us revisit Example 2, and identify my version of the Hungarian Convention,
for example, the variables strXP objNew and intComputerNum.

' ComputerLots.vbs
' Sample VBScript to create 10 Computers
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.4 - September 2005
' ----------------------------------------------------------------
Option Explicit
Dim objNew, objRootDSE, objContainer, objComputer
Dim intComputerNum, strXP
strXP = "XPMachine"

Set objRootDSE = GetObject("LDAP://rootDSE")


Set objContainer = GetObject("LDAP://cn=Computers," & _
objRootDSE.Get("defaultNamingContext"))

For intComputerNum = 1 To 3
objNew = strXP & intComputerNum
Set objComputer = objContainer.Create("Computer", "cn=" & objNew)
objComputer.Put "sAMAccountName", objNew & "$"
objComputer.Put "userAccountControl", 4096
objComputer.SetInfo
Next
intComputerNum = intComputerNum -1
WScript.Echo intComputerNum & " new computers created "

Learning Points
Note 1: VBScript is an object based language, therefore I prefix the names of
my Container and Computer objects with obj, e.g. objComputer.

Note 2: when I need a numeric variable, I prefix it with int e.g.


intComputerNum, other writers would use iComputerNumber. Incidentally, it
constantly surprises me that VBScript relies on pure logic more than pure maths.

Note 3: When it comes to values, many of my variables rely on names, so I


prefix them with str, short for 'string variable' e.g. strXP.

Summary of VBScript Variables


Choose meaningful names for your variable, select a word or words that describe
the purpose of the variable. Best practices suggests the length should be about 8
- 16 characters. strXP gives you a clue that this could be an XP name, while
objComputer is fairly self-evident.

This page covered the following VBScript methods, commands and


syntax:

String Variables, Number Variables, Object Variables, also For .... Next (Loop)
and .Create("Computer...")

Page 13 of 59
Introduction to VBScript.doc By Guy Thomas

Section 3 Create an OU (Organizational Unit) in Active


Directory

Build your container object

Tutorial for Creating an OU (Organizational Unit) with VBScript


This script builds on the knowledge of variables covered in section 2. It also
extends the .Create("Computer...") method to .Create("Organizational Unit...").
As promised in section 2, here is where we concentrate on Active Directory
techniques such as binding the RootDSE namespace.

When I visit companies, it surprises me that only 50% of network managers


create any OUs in their Active Directory. The rest keep all their
accounts in the Users (or Computers) container. The distinction
between OUs and container objects is not just a matter of a
strange book symbol on the OU, see Accounts OU on diagram
opposite. OUs are great for not only organizing your user
accounts, but also OUs make it easier to fine-tune your group
policies. (You cannot create or assign Group Policies to the Users or Computers
containers.)

When you start scripting Active Directory objects it is important to distinguish


between an OU and a Container object. It is easy to make a mistake and try to
write, CN=Accounts, or OU=Computers, when it should be OU=Accounts and
CN=Computers. (See diagram above.)

Topics for Creating an OU (Organizational Unit) with VBScript


Our Mission and Goal
Example 1 - Create a Top Level OU
Example 2 - Create a Child OU
Example 3 - Adding error-correcting Code
Summary for Creating User Accounts

Our Mission and Goal


Unlike the FileSystemObject, or Network scripts, this mission requires access to
an Active Directory domain. While we create OUs (Organizational Units) primarily
as containers to organize users, let us take the opportunity and learn about
scripting commands such as: 'Set, Create(Object), Get(Object) and .SetInfo'.

The subsidiary reason for studying OUs is preparing for that day when you need
to alter objects in that OU with a VBScript. There are traps for the unwary; for
example, you need to ensure that your script binds, not to the Users container,
but binds to a named OU.

Example 1 - Create a Top Level OU


Please would you inspect Active Directory Users and Computers and confirm that
there is no tiny book symbol on your Users folder. My point is that Users is a
container object, referenced by CN=Users and not an OU referred to by:
OU=Users.

Page 14 of 59
Introduction to VBScript.doc By Guy Thomas

Meanwhile, back to the main goal, creating a top level OU with VBscript.

Page 15 of 59
Introduction to VBScript.doc By Guy Thomas

Instructions

1. Important: Which OU will create? My script uses OU=Accounts to


generate an Organizational Unit called accounts. If you prefer a different
OU name, then change line 10 in your script.
2. Copy and paste the script below into notepad.
3. Save the file with .vbs extension e.g. Accounts.vbs.
4. Double click and examine the message boxes.
5. Open Up your Active Directory Users and Computers and inspect the OUs.

' Account.vbs
' VBscript to create an OU (Organizational Unit)
' Note two steps to set domain
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.3 - September 2005
' ----------------------------------------------------------'
Option Explicit
Dim objRoot, objDomain, objOU
Dim strContainer

strContainer ="OU=Accounts"

' Section to bind to YOUR Active Directory.


Set objRoot = GetObject("LDAP://rootDSE")
objDomain = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & objDomain)

' Section to create the OU defined by strContainer


' Also note the use of: .SetInfo

'On Error Resume next


Set objOU = objDomain.Create("organizationalUnit", strContainer)
objOU.SetInfo

WScript.Echo "New Top Level OU created = " & strContainer


WSCript.Quit

Learning Points - Binding to Active Directory


Building on my theme of mastering VBScript commands, I would like to draw
your attention to the following section of the Example 1 script.

' Section to bind to YOUR Active Directory.


Set objRoot = GetObject("LDAP://rootDSE")
objDomain = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & objDomain)

Page 16 of 59
Introduction to VBScript.doc By Guy Thomas

Note 1: GetObject() retrieves data. Later, in the full script we will make a new
OU with the sister command CreateObject().

Note 2: The 'Set' Command means that the variable called objRoot points to the
base of the LDAP name space. Think of rootDSE as tunnelling down into the
heart of Active Directory and then returning with information. In this instance,
naming information.

Note 3: DefaultNamingContext is a wonderful command because it removes my


need to know your domain. Without this technique, we would have to hard code
the domain name. Thanks to DefaultNamingContext, the script retrieves the
distinguished name automatically, in my case it would be: dc=cp, dc=mosel. (DC
= Domain Context, not Domain Controller). While, I do not know the name of
your domain, when the script runs on your machine it automatically extracts the
name of your domain. Clever.

Note 4: You may see other people's scripts, which Set ObjDomain with one line
instead of two. I admit that it is possible to write tighter code, but my way helps
us to breakdown the stages of binding to Active Directory. As you will see, I am
keen on scripts which employ the 'salami' technique to slice a task into
manageable stages.

Learning Points - Creating the actual OU


Here is the section which creates and then saves the new OU.

strContainer ="OU=Accounts"

'On Error Resume next


Set objOU = objDomain.Create("organizationalUnit", strContainer)
objOU.SetInfo

Note 1: Guy loves variables, so here is the name of the variable which holds the
OU name:
strContainer ="OU=Accounts"

Note 2: Observe the use of the 'Set' command, as in Set objOU.

Note 3: What the script is saying is this, start with the domain (objDomain),
now create a new OU (Not a user or a computer). Next, the script extracts the
name of the new OU from the strContainer variable.

Note 4: Another member of the Set family is .SetInfo. Take special note of
.SetInfo because overlooking this command can mean that the script runs
silently, without error, but unfortunately, nothing actually gets created! Omitting
.SetInfo is rather like filling in the dialog boxes, but forgetting to click the OK
button.

Page 17 of 59
Introduction to VBScript.doc By Guy Thomas

Example 2 - Create a Child OU


The idea of this VBScript example is to create a child OU. My assumption is that
you have already made a parent or top level OU as described in Example 1.

Creating a child OU is simple but there is a classic trap. Which of these two
sequences should you use?

strContainer = parent, child.


or strContainer = child, parent?

Answer: strContainer = child, parent

Assuming that the parent is called Accounts, here is a real example:


strContainer ="OU=Child,OU=Accounts". See diagram opposite.

Some people find this sequence counter intuitive, others, try both ways and see
which works. The gifted deduce the sequence from first principles. If you had to
add the user name, then the full DN (distinguished name) would be:
cn=guyt,OU=Child,OU=Accounts,dc=cp,dc=com. When you see the full path, the
sequence "OU=Child,OU=Accounts", becomes obvious.

Tip: When scripting OUs, pay particular attention to the placement of commas.
To create a child OU we just need one comma in the string variable. (In other
cases, but not here, we need two commas.)

' VBscript to create a child OU (Organizational Unit)


' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.3 - September 2005
' ----------------------------------------------------------'
Option Explicit
Dim objRoot, objDomain, objOU
Dim strContainer
err.number = vbEmpty

' Section to create the OU defined by strContainer


strContainer ="OU=Child,OU=Accounts"

' Section to bind to YOUR Active Directory.


Set objRoot = GetObject("LDAP://rootDSE")
objDomain = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & objDomain)

On Error Resume next


Set objOU = objDomain.Create("organizationalUnit", strContainer )
objOU.Put "Description", "Guy's OU"
objOU.SetInfo

' Confirmation Message


If Err.Number = vbEmpty Then
WScript.Echo "New Child OU created = " & strContainer
Else
WScript.Echo "Problem: " & err.number
End If
WScript.Quit

Page 18 of 59
Introduction to VBScript.doc By Guy Thomas

Learning Points - Creating the Child OU


Note 1: The key way to control this script is through the strContainer variable.
To create the child OU I amend:
strContainer ="OU=Child,OU=Accounts"

Note 2: With Err.Number, I have added primitive error-correcting code in


preparation for Example 3.

Example 3 - Adding error-correcting Code


As with every-day life, I always like to anticipate what could go wrong in my
scripts. Specifically, I want the script to handle two situations:
1) Where the child OU already exists
2) The situation where there is no Parent OU

To handle the errors, I divided the OU path into strParent and strContainer. Most
of the error-correcting takes place in the subroutine called GuyError().

' VBscript to create a child OU (Organizational Unit)


' With error-correcting code
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.4 - September 2005
' ----------------------------------------------------------'
Option Explicit
Dim objRoot, objDomain, objOU
Dim strContainer, strParent
err.number = vbEmpty

' Section to bind to YOUR Active Directory.


Set objRoot = GetObject("LDAP://rootDSE")
objDomain = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & objDomain)

' Section to create the OU defined by strContainer


strParent ="OU=Accounts"
strContainer ="OU=Child," & strParent

On Error Resume next


Set objOU = objDomain.Create("organizationalUnit", strContainer )
objOU.Put "Description", "Guy's OU"
objOU.SetInfo

' error-correcting Code


If Err.Number <> vbEmpty Then
Call GuyError
Else
WScript.Echo "New Child OU created = " & strContainer
End If
WScript.Quit(0)

' error-correcting code to create Parent OU


Sub GuyError()
If Err.number = "-2147019886" then
Wscript.Echo "Child OU already created"
WScript.Quit(1)
Else
Wscript.Echo "Error " & Err.number
Set objOU = objDomain.Create("organizationalUnit", strParent )
objOU.Put "Description", "Guy's Bulk Users OU"
objOU.SetInfo
Set objOU = objDomain.Create("organizationalUnit", strContainer )
objOU.SetInfo
WScript.Echo strParent & " Child and Parent OU Created "
End If
End Sub

Page 19 of 59
Introduction to VBScript.doc By Guy Thomas

Note 1: Firstly, I researched the specific err.number for the situation where the
OU already existed, the answer turned out to be -2147019886. In the WSH
Message box you actually see, Error: 80071392. (To check the math launch
Calc.exe in Scientific Calculator mode. Now compare 80071392 Hex with
2147019886 decimal)

Note 2: All scripting languages have sub-routine functions, I challenge you to


trace how 'sub GuyError()' makes use of strParent and strContainer.

Summary Creating an OU
It is surprising how often you need an OU. For example, testing Group Policies or
testing Logon Scripts. There again, perhaps you just want to organize your
accounts in Active Directory Users and Computers. It's worth remembering that
while I call it OU, Microsoft give the object its full name Organizational Unit.

My script will build your Active Directory Organizational Unit. All you need to do
is adjust the variable:
strContainer = "OU = Accounts". If you have the time, then go through the
script searching for all the script commands. Should there be any methods or
verbs that you do not understand, do refer to the learning points.

This page covered the following VBScript methods, commands and


syntax:

.Create(organizationalUnit", If...then... else...End If, Child and Parent OUs, sub


GuyError(), err.number

Page 20 of 59
Introduction to VBScript.doc By Guy Thomas

Section 4 Create a User in Active Directory

Bind to Active Directory

Introduction to Create a User in Active Directory


Creating Active Directory objects is a fertile area for VBScript. My suggestion, or
even challenge is to search for common ground in all Active Directory type of
scripts. For example, each Active Directory script 'binds' to the root of the
domain name space. Invariably, Guy's scripts employ a strContainer variable to
control the OU where the new object will be born. Production scripts also need a
loop. After all the reason that we are scripting rather than performing the same
task manually is to save time with routines that automate.

Tutorial for Creating a User Account with VBScript


This page has VBScript examples to show you how to create User accounts in
your domain. I urge you to take on board my advice to build your scripts in
stages. The benefit of creating scripts in small sections is that not only do you
understand each part, but also your brain will see ways of applying a section in a
different scenario. For example, once you learn how to bind with Active Directory
to create a User object, it's easy to modify the script and create a Contact object
instead.

Topics for Creating a User Account with VBScript


Our Mission and Goal
Example 1: Script to Create a User in Active Directory
VBScript Tutorial - Learning Points
Example 2: Script to Create a User in a Named OU
Summary for Creating User Accounts

Our Mission and Goal


Our first goal is to create a User account
in Active Directory's Users container. A
more realistic mission is to create users in
a named OU, and we will tackle that goal
in Example 2.

Breaking down the task of creating a user

Whilst our mission is to create a user in an OU, the teaching progression is to


create one user in the default Users container, then modify the script to deliver
the account to an OU, which we control with strContainer.

Declare the variables.


Bind to active directory.
Add the sAMAccountName.

Additional tasks not covered here.

Enable the account.


Add other properties, for example sn, office.
Add a loop to create multiple users.
Read names and other attributes from a spreadsheet.

Page 21 of 59
Introduction to VBScript.doc By Guy Thomas

Example 1 - Script to Create a User in Active Directory


In this script, we concentrate on the essential VBscript commands necessary to
build a User account in Active Directory Users and Computers. For example,
GetObject("LDAP://rootDSE") and .Create("User"). Even though I am
experienced at creating VBScripts, I still run manually through creating the object
in Active Directory Users and Computers. What I find is the GUI's menus, actions
and dialog boxes help me to rehearse the corresponding stages in my script.

Prerequisites
I recommend that you logon at a domain controller. If you are a long way from
the server, Remote Desktop would be a suitable alternative. If that is not
possible, you could get these scripts to work from an XP machine as a non-
administrator. However, why introduce extra complications? Especially at the
beginning, you want easy success, with fewest obstacles.

Instructions for Creating a User Account in Active Directory

1. You should run this VBScript on a Windows Active Directory domain.


2. Copy and paste the example script below into notepad or a VBScript
editor.
3. Decide whether to change the value for strUser. DomGuy2 is not a
particularly attractive name.
4. Save the file with a .vbs extension, for example: Users .vbs.
5. Double click Users .vbs and check the Users container for strUser.

Script to Create a User in a Named OU (Organizational Unit)

' Users .vbs


' Sample VBScript to create a User in Users .
' Author Guy Thomas http://Computerperformance.co.uk/
' Version 1.3 - May 2005
' ------------------------------------------------------'
Option Explicit
Dim strUser
Dim objRootLDAP, objContainer, objNewUser
strUser = "DomGuy2"

' Bind to Active Directory, Users container.


Set objRootLDAP = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://cn=Users," & _
objRootLDAP.Get("defaultNamingContext"))

' Build the actual User.


Set objNewUser = objContainer.Create("User", "cn=" & strUser)
objNewUser.Put "sAMAccountName", strUser
objNewUser.SetInfo

WScript.Quit

' End of Sample Create Users VBScript.

Page 22 of 59
Introduction to VBScript.doc By Guy Thomas

VBScript Tutorial - Learning Points


Note 1: The first 10 lines explain the purpose of the script and declare the
variables.

Note 2: The simple, but clever command, which allows the script to work with
any domain is: GetObject("LDAP://rootDSE"). Crucially, this statement binds
WSH / VBScript to Active directory. The next line puts the focus on the Users
container, as that is where the user will be born. Incidentally, the correct syntax
is cn=users, whereas OUs that you create need the OU= prefix, for example
OU=Accounts,.

Note 3: sAMAccountName controls the logon name, this is the name that users
should enter in the dialog box after they press the Ctrl Alt Delete, logon
sequence.

Note 4: .Create is a method to build an object. See how we script "User" not
"Computer" or "OU".

Note 5: When creating or modifying users, invariably you need .put and
.SetInfo. The .put method is the equivalent of selecting a box in Active Directory
Uses and Computers, in this example, sAMAccountName sets the correct property
and .put unloads the value set by strUser. .SetInfo is the VBScript equivalent of
pressing the OK button in the GUI. In both cases, it represents the final act of
creating or modifying the User object.

Note 6: This script represents 'work in progress'. For a real production script
you would need to enable the account, and most likely, add several other
properties, for example givenName. My desire is to get you started. Build the
script in stages, understand each component, then add another section.
Incidentally, I have an ebook dedicated to all aspects of bulk importing users
from data in a spreadsheet.

Page 23 of 59
Introduction to VBScript.doc By Guy Thomas

Example 2: Script to Create a User in a Named OU (Organizational


Unit)
Prerequisites

Create a new OU. I called my OU Accounts, what name will you choose?

Instructions for Creating a User Account in a Named OU

1. Copy and paste the example script below into notepad or a VBScript
editor.
2. Find the strContainer, and then change to the name of your OU.
3. Decide whether to change the value for strUser.
4. Save the file with a .vbs extension, for example: UserOU.vbs.
5. Double click UserOU.vbs and check the Computers container for
strComputer.

' UserOU.vbs
' Sample VBScript to create a User in a named OU.
' Author Guy Thomas http://Userperformance.co.uk/
' Version 2.4 - September 2005
' ------------------------------------------------------'
Option Explicit
Dim objRootLDAP, objContainer, objUser, objShell
Dim strUser, strName, strContainer

strUser = "BookKeeper21"
strName = "Bookie"
strContainer = "OU=Accounts ," ' Note the comma

' Bind to Active Directory, Users container.


Set objRootLDAP = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://" & strContainer & _
objRootLDAP.Get("defaultNamingContext"))

' Build the actual User.


Set objUser = objContainer.Create("User", "cn=" & strUser)
objUser.Put "sAMAccountName", strUser
objUser.Put "givenName", strName
objUser.SetInfo

' Optional section to launch Active Directory Uses and Users


Set objShell=CreateObject("WScript.Shell")
objShell.Run "%systemroot%\system32\dsa.msc"

WScript.Quit

' End of Sample UserOU VBScript.

VBScript Tutorial - Learning Points


Note 1: The key difference between the two scripts is: strContainer =
"OU=Accounts ,". Trace how VBScript applies this variable to set the
Organizational Unit.

Note 2: The following command looks easy to script: GetObject("LDAP://" &


strContainer & _. However it took me ages to get the speech marks and
ampersands (&) just right.

Page 24 of 59
Introduction to VBScript.doc By Guy Thomas

Note 3: objShell.run. This optional section is merely me having a little fun.


What this section does is open the Active Directory Users and Computers MMC
ready for you to inspect the new User account. My other reason for adding this
code is show that the script has executed successfully; otherwise, I just sit and
wonder if VBScript has finished interpreting all the commands.

Note 4: I suggested in Example 1 that you could add other attributes, trace how
I added givenName through strName. To see what I mean, I suggest that you
alter the value from "Bookie" to a more realistic name.

Summary of Creating User Accounts


The first example script shows you how to create a new user account in the
default container of Windows domain. In the second example, we control the
name of the OU where the account appears in Active Directory Users and
Computers. The tutorial's hidden agenda is learning how to apply the VBScript
object, methods and value technique. There is one other guiding principle, start
simply. Build complex scripts in stages.

This page covered the following VBScript methods, commands and


syntax:

Set objRootLDAP = GetObject("LDAP://rootDSE") .Create("User"), .Put and


.SetInfo

Page 25 of 59
Introduction to VBScript.doc By Guy Thomas

Section 5 Map Network Drive

Map a Network Drive - A Classic task for a VBScript.

Introduction to MapNetworkDrive
The practical task of this script is to map a network share to a local drive letter.
The best example of this tactic is when users access their home folder on a
server, via a drive letter. Unlike the Active Directory scripts, this script should
execute on any machine.

VBScript has a whole family of methods, which manipulate the network just as if
you used the Windows Explorer; look out for the line which builds the VBScript
object: CreateObject("WScript.Network"). The scripting spotlight on this page
falls on a VBScript method called MapNetworkDrive. On the next page we will
examine the parallel method called AddWindowsPrinterConnection, which maps
printers. Similar methods (not covered here) include, RemoveNetworkDrive and
EnumNetworkDrives.

Topics for MapNetworkDrive


Our Mission and Goal
Example - MapNetworkDrive VBScript Method
Learning Points for MapNetworkDrive
Guy's Challenges
Summary of MapNetworkDrive

Our Mission and Goal


Our mission is to map a network drive. Users may think that their home drive is
a local H:\, but you and I realize that the H:\ is a mapping which represents a
folder on a server. There is only a slim chance that a user would know how to
create this H:\ drive manually. Moreover, the chances of them remembering to
create the drive mapping every time they logon are practically zero.
Consequently, this is a job for a VBScript that runs automatically at logon.
Incidentally, I have an ebook dedicated to all aspects of logon scripts if you want
more detail. This page is all about getting you started with VBScript.

MapNetworkDrive Method

MapNetworkDrive follows the VBScript format of object, method, and value.


Firstly, we create the network object called objNetwork. Next we employ the
MapNetworkDrive method to create the local drive letter. For our examples, we
deploy MapNetworkDrive with two arguments, drive letter and UNC path. You
can observe in the examples that each argument is controlled by its own variable,
strDriveLetter = "H:" and strRemotePath = "\\alan\home".

Page 26 of 59
Introduction to VBScript.doc By Guy Thomas

Example - MapNetworkDrive VBScript Method


A reminder, our objective is to map a drive letter to a network path. In this
example, H:\ maps the UNC path \\server\share. Please note that the reason
this script works for me is that my share name is called, '\home' and my server is
'\\alan. Consequently, my UNC path for the variable strRemotePath =
"\\alan\home".

Pre- requisites.

1. On Line 10, change the server name from '\\alan' to your server name.
2. Make sure that your server has a share called '\home'.

Instructions to MapNetworkDrive

1. Copy and paste the script below into notepad.


2. Check strPath, your server is unlikely to be called "\\alan, so amend to the
name of your server.
3. Save the file with .vbs extension e.g. MapNetworkDrive.vbs.
4. Double click your script and check in your Windows Explorer for a new
drive called: home on 'alan' (H:).

'
' MapNetworkDrive.vbs
' VBScript to map a network drive to a UNC Path.
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.4 - September 2005
' -----------------------------------------------------------------'
Option Explicit
Dim objNetwork
Dim strDriveLetter, strRemotePath
strDriveLetter = "H:"
strRemotePath = "\\alan\home"

' Purpose of script to create a network object. (objNetwork)


' Then to apply the MapNetworkDrive method. Result H: drive
Set objNetwork = WScript.CreateObject("WScript.Network")

objNetwork.MapNetworkDrive strDriveLetter, strRemotePath


WScript.Quit

' End of Example VBScript.

Learning Points for MapNetworkDrive


Note 1: VBScript is an object based scripting language. On line 14, you can see
how the code creates objNetwork. Line 16 then
applies the famous MapNetworkDrive method to
achieve the actual drive mapping.

Note 2: If you run the script a second time, then


you get WSH error message code 80070055. The
temporary solution is to launch Windows Explorer,
and then delete the appropriate mapped drive. In
my example, right click on: home on 'alan' (H:) and
select: Disconnect. (See diagram opposite.) Now
you can run the script again. A better solution is to
add error-correcting code, however, for now, I want
to focus on one goal, mastering MapNetworkDrive.

Page 27 of 59
Introduction to VBScript.doc By Guy Thomas

Note 3: At the top of the script is a heading section. The idea of the header is
to explain what this VBScript will achieve. Some scriptwriters feel that the Dim
statements, which declare variables, are also part of the header section.

Note 4: Option Explicit is a VBScript command to force me to declare variables.


Not only is this 'best practice', but in my case, it alerts me to typos when I try to
use the same variable later in the script.

Note 5: Once we declare strDriveLetter, then we can assign it a value, in this


case "H:". One perennial problem I have with scripting is paying attention to
detail, especially the syntax. Even with the simple drive letter - H, we must be
careful. For the script to succeed we need precisely "H:". Neither "H:\", nor
"H\:" will work.

Guy's Challenges
MapNetworkDrive provides an ideal vehicle to explore the personality of
VBScript. Discover what you can change, and what is fixed by VBScript. My
advice is to start by changing strDriveLetter = "H:" to strDriveLetter = "L:" (or
any other available letter). I will be surprised if you fail to map the UNC path to
the new letter.

Try changing strDriveLetter to plain strLetter. You should get this working, but
only if change strDriveLetter not once, but in three places. If you accept this
challenge then Option Explicit will keep you on track. The point is that you have
control over the name of the variable.

You could try changing MapNetworkDrive to MapMyHomeDrive, or you could just


accept my assurance that you cannot just invent methods to manipulate WScript
objects. Instead, you have to learn the rich variety of built-in VBScript methods.
My message is never miss an opportunity to learn the name of method, for
example, EnumNetworkDrives, RemoveNetworkDrive and of course
MapNetworkDrive.

Summary of MapNetworkDrive
MapNetworkDrive is the classic method that logon scripts employ to provide home
directories. Once you master this VBScript, which maps drive letters to UNC
shares, you can extend your range to mapping printers.

This page covered the following VBScript methods, commands and


syntax:

Key VBScript term: MapNetworkDrive, observe this method:


CreateObject("WScript.Network")

Page 28 of 59
Introduction to VBScript.doc By Guy Thomas

Section 6 Map a Network Printer

Map a Network Printer and also set the Default Printer

Introduction to AddWindowsPrinterConnection Logon Script


One of the jobs of a Windows logon script is to provide applications such as Word
or Excel with a suitable network printer. I will show you how to build a VBScript
that uses the AddWindowsPrinterConnection method to create a printer. As a
bonus, I have a second script that adds code to set the default printer. You
probably cannot help spotting similarities between these scripts and mapping a
network drive in section 5. For example, CreateObject("WScript.Network")

Topics for AddWindowsPrinterConnection Scripts


Our Mission
Example 1 Simple Printer Script with AddWindowsPrinterConnection
Example 2 Full Printer Script with AddWindowsPrinterConnection
Example 3 - SetDefaultPrinter
Printer Logon Script Summary

Our Mission
Our mission is to create a script, which
provides the user with a connection to a
shared printer. As so often happens, the
script mimics your manual actions, in this
instance adding a network printer in the
Printers (and Faxes) folder.

Printer Methods

Printer VBScripts follow the classic format of object, method, and value. We
create the network object called objNetwork. Next, we employ the
AddWindowsPrinterConnection method to create the network printer. Finally, we
get a new printer icon in the Printers and Faxes folder, which matches the value
set in strUNCPrinter. What gives any scripting language its power is the methods
or verbs, in this case AddWindowsPrinterConnection, in other scripts
SetDefaultPrinter or even RemovePrinterConnection.

Example 1 - Simple Printer Script with


AddWindowsPrinterConnection
Our objective is to create a printer icon, which connects to the network printer
called \\zara\HP LaserJet. Printer scripts employ a variety of different methods; in
this instance, we concentrate on AddWindowsPrinterConnection. If you have
Windows 2003 or XP clients, the procedure is straightforward; this method only
needs one parameter or argument, namely the UNC path to the shared printer.
For example:
AddWindowsPrinterConnection strPrinterUNCPath

Note that in the case of Windows 2003 and XP clients, there is no argument to
specify the driver; the client will automatically download the correct driver from
the print server.

Page 29 of 59
Introduction to VBScript.doc By Guy Thomas

Pre- requisites for Mapping Printers

You need a machine (server) with a shared printer.

Instructions for a simple Printer Logon Script

1. Copy and paste the script below into notepad.


2. Change the server name from "\\zara to the name of your print server.
3. Create a shared printer and use that name in place of \HP LaserJet in my
script.
4. Save the file with .vbs extension e.g. Printers.vbs.
5. Double click and then launch your Printers folder.

'
' Printers.vbs - Windows Logon Script.
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection "\\zara\HP LaserJet"

Learning Points
Note 1: I do realize that scripts go wrong. However, with printer scripts, it s
often the result of 'over-think', so begin with simple plan and pay attention to the
syntax. In this instance, there is one method AddWindowsPrinterConnection and
one parameter or argument, the UNC path to the network printer "\\zara\HP
LaserJet".

Note 2: This basic script needs no commas. I mention this as another example
of keeping it simple, don't go into 'over-think' and add unnecessary commands.

In addition, there is no need for an argument to set the printer driver or port
number, the server will take care of that business automatically.

Note 2: This script conforms to the classic VBScript structure, object, method,
and value. We create a network object, objNetwork, apply the
AddWindowsPrinterConnection method and then assign the value of your shared
network printer.

Note 3: I deliberately made Example 1 as short as possible so that it would


highlight the essential commands. Normally, I include a header section and
declare variables, as you will see in Example 2.

Page 30 of 59
Introduction to VBScript.doc By Guy Thomas

Example 2 - Printer Script with AddWindowsPrinterConnection


This script has the same core commands as the first example but with a few extra
coding niceties. As you get to know my VBScript style, so you will see my
familiar heading section, liberal use of variables and a WScript.Echo message box
to confirm what has happened.

' PrintersLong.vbs - Windows Logon Script.


' VBScript - to map a network printer
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.3 - September 2005
' -----------------------------------------------------------------'
Option Explicit
Dim objNetwork, strUNCPrinter
strUNCPrinter = "\\zara\HP LaserJet."
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection strUNCPrinter
WScript.Echo "Check the Printers folder for : " & strUNCPrinter

WScript.Quit

' End of Guy's Windows logon script.

Learning Points
Note 1: Option Explicit forces us to declare variables before we use them in the
VBScript. The idea is to reduce spelling mistakes.

Note 2: One reason that I like to employ variables is to make it easier to


troubleshoot in general and display messages with WScript.Echo in particular.

Example 3 - SetDefaultPrinter
As you may know, I believe in building up scripts in stages. However, once you
have created two or three printers you probably want to control which printer is
the default. Thus, setting a default printer is a natural progression, and any
production script would have both methods, AddWindowsPrinterConnection and
SetDefaultPrinter.

Scripting printers is easy because there are fewer parts to each command. In the
case of SetDefaultPrinter, we need only the name of the printer - that is all. Here
is the SetDefaultPrinter method and its one argument:

Page 31 of 59
Introduction to VBScript.doc By Guy Thomas

Instructions to SetDefaultPrinter

1. Copy and paste the script below into notepad.


2. Save the file with .vbs extension e.g. SetDefaultPrinter.vbs.
3. Double click the script and check your Printers folder. Which is printer is
now the default.

'
' SetDefaultPrinter.vbs - Windows logon script example
' PrintersDefault.vbs - Set the default printer
' VBScript - to map a network printer
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.4 - April 24th 2005
' -----------------------------------------------------------------'
Option Explicit
Dim objNetwork, strUNCPrinter
strUNCPrinter = "\\zara\HP LaserJet 2420"
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection strUNCPrinter

' Here is where we set the default printer to strUNCPrinter


objNetwork.SetDefaultPrinter strUNCPrinter
WScript.Echo "Check the Printers folder for : " & strUNCPrinter

WScript.Quit

' End of Guy's Windows logon example VBScript.

Learning Points
Note 1: The basic SetDefaultPrinter is a short command with no commas and
only one argument - the printer share name.

Note 2: Surprisingly, you do not need to know the whereabouts of the print
server.

Note 3: To see this script to best effect you need a third printer, which is initially
set to the default printer. The good news is that you can play 'fantasy printers'.
Just call for the printer wizard and pretend that you have an Epson xyz or a
Lexmark 123ABC, just to practice your scripting.

Summary of AddWindowsPrinterConnection
Mapping Printers is an important application of VBScript. All you need to
experiment with this script is a shared network printer. Incidentally, in a
production script it costs little to add an extra line of code, which explicitly sets
the default printer.

From a pure scripting point of view, this script teaches the VBScript rationale of
creating an object and then using methods to perform useful tasks such as
connecting to a network printer and then setting the default printer.

This page covered the following VBScript methods, commands and


syntax:

Key VBScript terms: AddWindowsPrinterConnection, SetDefaultPrinter, Key


method:
CreateObject("WScript.Network").

Page 32 of 59
Introduction to VBScript.doc By Guy Thomas

Section 7 Create a Folder (Stage 1 of 3)

Store those scripts

Introduction to Create Folders


One of my favourite strategies with scripts is taking a section from one script and
pasting it into another script. This is my point, regard the script on this page as
the first stage in bolting three scripts together. The result in section 9 will be one
big script, which creates a folder, a file and then appends text to that file. I
admit that this is a difficult project so early in your scripting career; however, I
want to make the scripts useful as well as instructional.

Topics for VBScript


Meet the VBScript terms
Example 1 - Basic VBScript to Create a Folder
Example 2 - Create a Folder with error-correcting
Code
Example 3 - Script to Create a Folder, then Open
Windows Explorer
Summary of Creating Folders

Meet the VBScript terms


Here is a reminder of the overall plan. In Stage 1, on this page, we build a
folder. Once we have created the folder, then in Stage 2 we can add a file,
finally, in Stage 3 I will show you how to write text to our file. As I mentioned
earlier, VBScript is a simple but powerful language. I would like to introduce the
VBScript commands that we will be employing:

1) Dim: Stands for dimension, it means I declare the variables.

2) Option Explicit: This does not achieve anything on it's own, however, it works
with to Dim to force us to declare all variables. The benefit of Option Explicit is
that it reduces errors caused by typos. For example, if we set strDirectory =
c:\logs but later referred to the variable as strDir instead of strDirectory, the
result would not what we expected.

3) strDirectory: Is a variable which holds the path to the new folder. Feel free to
amend c:\logs to a different folder or even an alternative drive, for example
(D:\vbscript) would work equally well as a place to hold your scripts.

4a) Set objFSO = CreateObject("Scripting.FileSystemObject"). This statement is


the heart of the script and needs careful dissection. As ever proceed slowly, inch
by inch and it will be a synch. Set objFSO means initialize the variable.

4b) CreateObject tells VBScript to create a new object rather than get an existing
object. Moreover, what we want is a scripting FileSystemObject and not a user or
a printer object. Think of FileSystemObject as defining the object, in this case, it
will have methods for manipulating folders.

Page 33 of 59
Introduction to VBScript.doc By Guy Thomas

5) Set objFolder = objFSO.CreateFolder(strDirectory) This powerful command


brings all our components together and finishes the job of creating the folder.
Think of objFSO, which we so carefully created on the previous line, as being a
magic source of new folders. All we need to do is to tell this magic object, to
CreateFolder (not CreateTextFile), and tell it what name to give the new folder
namely the value held by the strDirectory variable.

6) WScript.Echo "Just created " & strDirectory. This is an optional instruction to


display a message, which reminds us what the script has done. As you will see, I
love WScript.Echo boxes, especially when the script is at the testing stage when
we want to confirm that VBScript has at least interpreted the previous lines of
code. Note in passing how I reuse the strDirectory variable. Observe if you
change strDirectory s value, the confirmation message changes to reflect the
name of the new folder.

Example 1 - Basic VBScript to Create a Folder


Be aware that this script works brilliantly - first time. You get the folder specified
by strDirectory, but if you run the script again, this time you get errors. My
work-around is to keep amending the value of strDirectory, for example, on the
second running change strDirectory = "C: \logs" to strDirectory = "C:
\logs\take2". However, I realize that this technique is no long-term solution, but
do not worry, in Example 2 we cure the problem with error-correcting code.

Prerequisites
This is a script that will execute equally well on a Windows server or an XP
machine. Should you get permission errors, I recommend that you logon as
administrator.

Instructions for Creating Folders

1. Copy and paste the example script below into notepad or a VBScript
editor.
2. Decide whether to change the value for strDirectory (Particularly the drive
letter).
3. Save the file with a .vbs extension, for example, NewFolder.vbs.
4. Double click NewFolder.vbs and check Windows Explorer for strDirectory.

Sample Script to Create a Folder

' NewFolder.vbs
' Sample VBScript to create a folder (Simple)
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.4 - September 2005
' ---------------------------------------------------------------'
Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "c:\logs"
' Create FileSystemObject. So we can apply .createFolder method
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Here is the key line Create a Folder, using strDirectory


Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
WScript.Quit
' End of Sample VBScript to create a folder

Page 34 of 59
Introduction to VBScript.doc By Guy Thomas

VBScript Tutorial - Learning Points


Note 1: CreateObject holds the key. What we want here is a FileSystemObject
object because it's suitable for making folders and files. My point is that for this
section, we don't need a network or an Active Directory object.

Note 2: Now what we need specifically is a folder. So, we apply the


.CreateFolder method to the objFSO and thus ensure that we get the desired
folder object (and not a file object).

Example 2 - Create a Folder with error-correcting Code


This script builds on Example 1 by adding error-correcting code, the benefit is
that the script now copes with situations where the folder already exists. One of
the quirks of VBScript is that adding error-correcting code often takes more effort
than creating the main task. Another advantage of adding the extra code is that
it makes you understand what is going. Writing error-correcting also teaches you
to anticipate what could go wrong.

From my spreadsheet days, I have always loved the 'If' function. In VBScript the
'If' construction may take five or more lines, it works like this:

1. If - test - then (the word 'then' ends the first line)


2. What should happen, if - test - is true
3. Else (a line unto itself)
4. What should happen if test was false
5. End If (on its own line)

' NewFolderEC.vbs
' Sample VBScript to create a folder with error-correcting Code.
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.6 - May 2005
' ---------------------------------------------------------------'

Option Explicit
Dim objFSO, objFolder, objShell, strDirectory
strDirectory = "c:\logs"

' Create the File System Object


Set objFSO = CreateObject("Scripting.FileSystemObject")

' Note If..Exists. Then, Else ... End If construction


If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
WScript.Echo strDirectory & " already created "
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
End If

WScript.Quit

' End of Sample VBScript to create a folder with error-correcting Code

Example 3 - Script to Create a Folder, then Open Windows


Explorer
Here is the icing on the cake. Not strictly necessary, but a final flourish that
opens Windows Explorer for you to check your newly created folder. First, get
the basic model to create the folder (Example 1). Then add error-correcting code
(Example 2) and finally, add 5 lines to open Windows Explorer.

Page 35 of 59
Introduction to VBScript.doc By Guy Thomas

' NewFolderEC.vbs
' Sample VBScript to create a folder with error-correcting Code.
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.6 - May 2005
' ---------------------------------------------------------------'

Option Explicit
Dim objFSO, objFolder, objShell, strDirectory
strDirectory = "c:\logs"

' Create the File System Object


Set objFSO = CreateObject("Scripting.FileSystemObject")

' Note If..Exists. Then, Else ... End If construction


If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
WScript.Echo strDirectory & " already created "
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
End If

' Extra section to open Windows Explorer


If err.number = vbEmpty then
Set objShell = CreateObject("WScript.Shell")
objShell.run ("Explorer" &" " & strDirectory & "\" )
Else WScript.echo "VBScript Error: " & err.number
End If

WScript.Quit

' End of Sample VBScript to create a folder with error-correcting Code

VBScript Tutorial - Learning Points


Note 1: objShell = CreateObject("WScript.Shell") is my way of demonstrating
that the script has achieved its goal. The active part is objShell.run. In this
example, it simulates you clicking on the Start (Menu), selecting Run and typing,
'Explorer'.

Note 2: You may have noticed that objShell is made by:


CreateObject("WScript.Shell") also it has a different job compared with objFSO,
which was built with FileSystemObject.

Note 3: At first don't worry about these different types of objects. Just work
smart, find a suitable example, copy the code, and amend to your
circumstances. After a while you will have your own library of scripts and can
start bolting together sections and building production scripts.

Summary of Creating Folders


We have covered a great deal of ground. In terms of theory you can appreciate
how VBScript employs the Object, method, value system. As far as script
structure is concerned, here is a classic example of declaring variables, creating
objects and manipulating properties. Another important lesson is to add error-
correcting code, in is important to anticipate what could go wrong, and ensure
that the script always quits gracefully.

This page covered the following VBScript methods, commands and


syntax:

FileSystemObject, .CreateFolder, .GetFolder, If...then...End if and also


CreateObject("WScript.Shell")

Page 36 of 59
Introduction to VBScript.doc By Guy Thomas

Section 8 Create a Text File (Stage 2 of 3)

How to create a file

A VBScript Tutorial for Creating a File


Think of this page as the middle of a trilogy leading from creating the folder to
adding text to the file. The examples on this page explain how to create a text
file. When you have created your file then I have another page showing you how
to write or append data. Before you tackle this page, I recommend that you
review Stage 1 to create a folder.

Topics for Writing or Appending to a File with VBScript


Our Mission and Goal for this Section
Example - Sample VBScript to Append Text to a File
VBScript Tutorial - Learning Points ForAppending
Summary of How to Append Data to a
Text File

Our Mission and Goal


Our mission on this page is to create a text
file. Naturally, we need a folder to hold our
file, therefore, our script will test to see if the
folder exists, and if not, then our code will
create a folder.

Example 1 - Basic VBScript to Create a File with CreateTextFile


The idea behind this script is to highlight the code need to create a file. The cost
of focussing on one method is that Example 1 works fine the first time you
execute the script, but if you run it a second time, you get an error. To cure the
problem, move on to the Example 2. A temporary solution is to keep altering the
strDirectory. Here is what I did as a work-around:

First Run strDirectory = "C: \logs"

Second Run strDirectory = "C: \logs\guy1"

Third Run strDirectory = "C:\ logs\guy2"

I admit this work-around is poor scripting, but my dilemma is keeping the code
simple, versus a slick script that is difficult to follow. To tell the whole truth, I
fervently believe that you learn more when scripts go wrong - providing you can
fix the error quickly.

Prerequisites
This is a script that will create a file equally well on a Windows server or an XP
machine. To ensure that there are no permissions errors, I recommend that you
logon as administrator.

Page 37 of 59
Introduction to VBScript.doc By Guy Thomas

Instructions for Creating Files

1. Copy and paste the example script below into notepad or a VBScript
editor.
2. Decide whether to change the values for strFile and strDirectory.
3. Save the file with a .vbs extension, for example: SummerFile.vbs.
4. Double click SummerFile.vbs and check Windows Explorer for strDirectory.

Sample Script to Create a File

' SummerFile.vbs
' Sample VBScript to create a file using FileSystemObject
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.7 - September 2005
' ---------------------------------------------------------------'

Option Explicit
Dim objFSO, objFSOText, objFolder, objFile
Dim strDirectory, strFile
strDirectory = "C:\logs\guy1"
strFile = "\Summer.txt"

' Create the File System Object


Set objFSO = CreateObject("Scripting.FileSystemObject")

' Create the Folder specified by strDirectory on line 10


Set objFolder = objFSO.CreateFolder(strDirectory)

' -- The heart of the create file script -----------------------


' -- Creates the file using the value of strFile on Line 11
' --------------------------------------------------------------
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "Just created " & strDirectory & strFile

Wscript.Quit

' End of FileSystemObject example: VBScript

VBScript Tutorial - Learning Points


Note 1: All FSO scripts begin by creating a File System Object with
CreateObject("Scripting.FileSystemObject"). You really do need the word
"Scripting"

Note 2: The specific method for creating the file is called: .CreateTextFile.
Observe that we also employed the sister method CreateFolder.

Note 3: By tracing strFile and strDirectory, you will appreciate how to employ
variables in VBScripts.

Note 4: If you run the script for a second time it generates the file exists error
800A003A. So, in Example 2 we are going to introduce error-correcting code.

Page 38 of 59
Introduction to VBScript.doc By Guy Thomas

Example 2 - Create a File with error-correcting Code


This script is much more productive than the primitive Example 1. My idea is to
anticipate situations where the folder already exists by adding extra code. We
are also going to employ a shell object (objShell) to run the Windows Explorer,
this means that we can see instantly whether the script worked as designed.

Sample Script to Create a File and Check if a File Already Exists

' SummerFileEC.vbs
' Sample VBScript to create a file with error-correcting Code
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.6 - June 2005
' ---------------------------------------------------------------'

Option Explicit
Dim objFSO, objFolder, objShell, objFile
Dim strDirectory, strFile
strDirectory = "C:\logs"
strFile = "\Summer.txt"

' Create the File System Object


Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the strDirectory folder exists


If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
End If

' Check whether strFile already exists.


If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "Just created " & strDirectory & strFile
End If

set objFolder = nothing


set objFile = nothing

' Section to open explorer so that you can see the new file
If err.number = vbEmpty then
Set objShell = CreateObject("WScript.Shell")
objShell.run ("Explorer" &" " & strDirectory & "\" )
Else WScript.echo "VBScript Error: " & err.number
End If

WScript.Quit

' End of VBScript to create a file with error-correcting Code

Page 39 of 59
Introduction to VBScript.doc By Guy Thomas

VBScript Tutorial - Learning Points


Note 1: If you do not add error-correcting code, then there is a real danger that
running the script again will destroy the original file. What .FileExists does is to
check to see if there is already a file with the name as that referenced by strFile.

Note 2: This script also contains code which protects against the folder already
existing - FolderExists.

Note 3: A tiny point, but originally the script produced a WSH error message.
The solution was to add set objFolder and objFile = nothing. Here is another
example where we learn more when things go wrong. I have known for a long
time that I should nullify objects when I have finished them, but idleness and
wanting to keep the script short have resulted in a sin of omission. Sometimes I
get away with it, but not in this example.

Note 4: objShell = CreateObject("WScript.Shell") is my way of showing that the


script has achieved its goal. The active part is objShell.run. In this example, the
script mimics you clicking on the Start (Menu), clicking on Run and then typing
'Explorer'.

Summary of Creating Files


With file system objects there is a natural progression, create the folder, then the
file, finally to read or write text into that file. This page shows you how to create
a file using the CreateTextFile method. Next step let us explore reading or
writing data to the file.

This page covered the following VBScript methods, commands and


syntax:

FileSystemObject, .CreateFile CreateFolder, .FileExists .FolderExists, objShell.Run

Page 40 of 59
Introduction to VBScript.doc By Guy Thomas

Section 9 Append Data to Text File (Stage 3 of 3)

Write Data to that file.

A VBScript Tutorial for Writing or Appending to a File


The examples on this page represent the climax of our mission to write data to a
file. To recap, the first task was to create the parent object - the folder. Then,
we created the child object - the files, now here in the following examples, we are
going to append text to our file. I recommend that you review Stage 2 to
create a file.

Whilst my examples are trivial, if you imagine these Examples as sections of a


larger script, then you will appreciate the versatility of the OpenTextFile.WriteLine
method.

Topics for Writing or Appending to a File with VBScript


Our Mission and Goal for this page
Example - Sample VBScript to Append Text to a File
VBScript Tutorial - Learning Points ForAppending
Summary of How to Append Data to a Text File

Our Mission and Goal


Often, at least in testing, you can just echo
output data to a message box. However, I
imagine in a production script that you want
to be writing or appending data to a text
(.txt) file, if so then OpenTextFile is the
method for you. Even though you can also
command OpenTextFile to read data, I would prefer to employ the
CreateObject("Excel.Application") method for reading text from a spreadsheet. In
summary, it's a case of horses for courses, OpenTextFile for writing,
Excel.Application for reading.

Example - VBScript to Append Text to a File


This is a long script, therefore, let us break the code into sections. The best
approach is to master the create folder and create file sections, before you
concentrate on our present mission, to write text to a file. Remember that our
script must locate the file. Also, remember that in turn, the file has a parent
object, the folder. Although the final bonus section is not strictly necessary, I
like file scripts to open explorer so that I can check the new data.

Before we start, there are three variations of the OpenTextFile method:

1) Reading the text.

2) Writing text (perhaps I should say over-writing text).

3) Appending data (as in leaving the existing text and adding more).

Page 41 of 59
Introduction to VBScript.doc By Guy Thomas

VBScript controls which variation of OpenTextFile you get with a special


constant. 'CONST' is a VBScript subject in its own right. However, for the
purposes of this script, I suggest that you just accept the CONST values and
focus on the OpenTextFile object and the .WriteLine method.

' OpenTextFile Method requires a Const value


' ForAppending = 8 ForReading = 1, ForWriting = 2
For this script I choose: ForAppending = 8

Prerequisites
This is a script that will execute equally well on a Windows server or an XP
machine. To ensure that there are no permissions errors, I recommend that you
logon as administrator.

Instructions for Creating Files

1. Copy and paste the example script below into notepad or a VBScript
editor.
2. Decide whether to change the value for strDirectory, strFile and strText.
3. Save the file with a .vbs extension, for example: AppendText.vbs
4. Double click AppendText.vbs and check Windows Explorer for strDirectory.

Page 42 of 59
Introduction to VBScript.doc By Guy Thomas

Sample Script to Append Text to a File

' AppendText.vbs
' Sample VBScript to write to a file. With added error-correcting
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.5 - September 2005
' ---------------------------------------------------------------'

Option Explicit
Dim objFSO, objFolder, objShell, objTextFile, objFile
Dim strDirectory, strFile, strText
strDirectory = "c:\logs"
strFile = "\Summer.txt"
strText = "Note pay another check to bank"

' Create the File System Object


Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the strDirectory folder exists


If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
End If

If objFSO.FileExists(strDirectory & strFile) Then


Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "Just created " & strDirectory & strFile
End If

set objFile = nothing


set objFolder = nothing
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 8

Set objTextFile = objFSO.OpenTextFile _


(strDirectory & strFile, ForAppending, True)

' Writes strText every time you run this VBScript


objTextFile.WriteLine(strText)
objTextFile.Close

' Bonus or cosmetic section to launch explorer to check file


If err.number = vbEmpty then
Set objShell = CreateObject("WScript.Shell")
objShell.run ("Explorer" &" " & strDirectory & "\" )
Else WScript.echo "VBScript Error: " & err.number
End If

WScript.Quit

' End of VBScript to write to a file with error-correcting Code

Page 43 of 59
Introduction to VBScript.doc By Guy Thomas

VBScript Tutorial - Learning Points


Note 1: This is a complex script built from two other scripts. If you have not
done so already, you may wish to recap: Stage 2 creates a file.

Note 2: As with many file scripts, the first task is to create an object. Once we
have that crucial object then we can persuade it to manipulate the text, here is
the classic FSO command:
Set objFSO = CreateObject("Scripting.FileSystemObject"). Once we create
objFSO, we can GetFolder and CreateTextFile.

Note 3: The central point of this script is the OpenTextFile method. What we
must also do is control whether to read, write or append (as in this case).
Examine carefully the CONST statement. This example uses:
Const ForAppending = 8.
However, if you wish to over-write the text in the file, the command is ForWriting
= 2, (not ForAppending = 2.

Note 4: You may well be asking, what is the point of an example such as this
script? Well, try to imagine a WMI script that has interrogated the operating
system for disk information. Would it not be better to write the complex data to
a file than merely echo the output to your screen?

Note 5: Without adding these two lines the VBScript fails with a permissions
error:
set objFile = nothing
set objFolder = nothing

Summary of How to Append Data to a Text File


This is the definitive FSO script. I am sure that you will find many opportunities
to adapt this VBScript code into a WMI script, or indeed any script, which requires
storing the output in a file.

If you have already learnt how to create files and folders, then the OpenTextFile
is the logical progression in controlling the data in the actual file. By fine-tuning
the 'CONST For xyz', you can append data or over-write the existing file. The real
power and joy of this FSO technique comes in projects where you want to store
the data permanently in a text file.

This page covered the following VBScript methods, commands and


syntax:

FileSystemObject, .WriteLine CreateFolder, GetFolder, If ... then.. end IF.

Page 44 of 59
Introduction to VBScript.doc By Guy Thomas

Section 10 Registry Scripting

Read and Write information to the Registry

Introduction Registry Scripting


Being even a minor expert at VBScript requires a variety of subsidiary skills.
Take scripting the registry as an example, in addition to mastering the .RegRead
and .RegWrite commands; you also need to be expert with Regedit and possible
Windiff. One of the benefits of being multi-skilled is that you can apply tricks
learnt in one project to another area. For instance, if you are familiar with how
the FSO objects read and write to files, then you can apply the same techniques
to the registry. Naturally, it also works the other way around, what you learn on
this page about interacting with the registry can be applied to writing Event Logs
to a textfile.

Topics for Registry Scripting


Mission to Read the Registry
Example 1 - To Extract Windows Version Information from the Registry
Mission to Write Keys to the Registry
Example 2 - To Write Information into the Registry
Summary - Scripting the Registry

Mission to Read the Registry


The purpose of the first example is to read the registry. The logic is simple,
namely to create a Shell object, manipulate it with the .RegRead method, and
then extract the registry values. Finally, we echo these values to a message box.

From a pure scripting point of view, I would like to highlight that the registry
scripts require a 'Shell' object rather than a 'Network' or 'FileSystem' Object. The
two key methods or verbs are .RegRead and .RegWrite. Therefore, keep an eye
out for objShell.RegRead and objShell.RegWrite.

Many registry paths can be very long. Therefore, to control lines of code greater
than 80 characters, the script uses the _ (Underscore). Remember that when
VBScript sees a carriage return, it thinks, 'this is a new line of code'. By ending a
line with _, you can effectively join two lines so that the script host (WSH)
interprets them as a single line of code. Another view of this solution is to regard
the _ as an escape character for the carriage return.

Example 1 - To Extract Windows Version Information from the


Registry
Instructions

1. Copy and paste the script below into notepad.


2. Save the file with .vbs extension e.g. ReadReg.vbs
3. Double click and then check the message box
4. You may like to run Regedit and navigate from the HKLM to the "Windows
NT\currentVersion\" section referenced by the script.

Page 45 of 59
Introduction to VBScript.doc By Guy Thomas

' ReadReg.vbs
' VBScript to read Operating system version from the registry.
' Author Guy Thomas http://computerperformance.co.uk
' Version 1.3 - September 2005
' ------------------------------------------------------------------'
'
Option Explicit
Dim objShell, objUNC, arrOS
Dim strVersion, strOS, strSP, strWinLogon

strOS = "ProductName"
strVersion ="CurrentVersion"
strSP = "CSDVersion"

strWinLogon = "HKLM\SOFTWARE\Microsoft\"_
& "Windows NT\currentVersion\"

Set objShell = CreateObject("WScript.Shell")

strOS = objShell.RegRead(strWinLogon & strOS)


arrOS = Split(strOS, " " )
strSP = objShell.RegRead(strWinLogon & strSP)
strVersion = objShell.RegRead(strWinLogon & strVersion)

Wscript.Echo "Operating System " & vbTab & strOS & vbCr _
& arrOS(1) & " version " & vbTab & strVersion & vbCr _
& "Service Pack " & vbTab & strSP

WScript.Quit

' End of script.

Learning Points
Note 1: This script employs a Shell object to manipulate the registry. Here is
the line that builds the object:
Set objShell = CreateObject("WScript.Shell").

Note 2: The featured method is .RegRead. This collects the information just as
if you had opened Regedit then copied the information.

Note 3: In the script, I shortened the registry hive: HKEY_LOCAL_MACHINE to


HKLM, this is a well know abbreviation, and it works well.

Note 4: Observe how I recycle the strWinLogon variable for three separate jobs.

Note 5: Study the use of vbCr (Visual Basic Carriage Return). Remember that
vbCr is merely for formatting text in the message box. vbCr is different from _
(underscore), which was for joining two lines in the script itself. You can also see
a sister command for a tab, as in vbTab. Here is a classic example of studying
vbCr and _, and by comparing and contrasting their usage, you get greater
insight into how each works.

Note 6: The Split command is an indulgence. From time to time, I like to add
extra frills which improve the output. Split, as the name suggests, breaks a
string. The string in question is "Microsoft Windows xyx". In this instance, we
employ a space with " " to split the string. In the output, arrOS(1) refers to the
second complete word "Windows". If you tried arrOS(0), it would return the first
word - Microsoft.

Page 46 of 59
Introduction to VBScript.doc By Guy Thomas

Challenges
My greatest joy would be if you adapted my script to read other registry values.
Extend the script to read not only from the WinLogon section, but also from the
many other folders in the registry. So, amend my script to read other values,
then echo the output to a message box.

Summary - Reading the Registry


Here is a simple script to read values from the registry. Even though the concept
is straightforward, take the time to understand the fine detail of the VBScript
command, for example vbCr, _(underscore) and & (ampersand).

This script's hidden agenda is attention to detail.

Mission to Write Keys to the Registry


You may have noticed a pattern with my scripts. Each script has two parts, a
clear practical goal, and a VBScript learning point. In this script, the practical
goal is to add a 'Welcome message' to the registry, the result will display in the
Logon dialog box. Meanwhile the learning point is to master the .RegWrite
method.

Example 2 - To Write
Information into the Registry
I want to introduce you to a registry
change that does not require a
reboot. The goal of this script is to
add a welcome message to the
logon dialog box. To save logging
off, you can see the very same
message by pressing Ctrl Alt
Delete. When the Windows Security
dialog box appears, read the top bar
and observe your strMessage.

My learning message is practice writing to the registry, but only by experimenting


with a risk-free area. The tactics are to create a new key called 'Welcome', then
assign it a string value, for example, 'This is Guy's Kingdom'. Before we examine
the .RegWrite syntax, you may notice that WScript creates a Shell object -
objShell. My point is become a collector of these WScript objects, Network,
FileSystemObject and now Shell. Perhaps it's me suffering from 'train-spotting'
but when ever I see a new script the first thing I look for is the objects, the
second think I look for is the methods or verbs such as .RegWrite.

The .RegWrite method has three parts (arguments):

1. The name of the registry Key that we are creating or writing to. Note the
slashes " \ ". In particular, notice that there is a " \ " after Winlogon\, but
not after Winlogon\Welcome.
2. The value itself e.g. "Guy's Kingdom"
3. The registry key type, e.g. REG_SZ (string) or REG_DWORD.

Page 47 of 59
Introduction to VBScript.doc By Guy Thomas

Example: objShell.RegWrite "HKLM\SOFTWARE\Microsoft\" _


& "Windows NT\currentVersion\Winlogon\Welcome", "Guy's Kingdom", "REG_SZ"

In the actual script, I control "HKLM\SOFTWARE\Microsoft\...." with the variable


strWinLogon

Another minor point is that because the key is so long, that I need an underscore
_ so that WScript sees my code as one complete line. Incidentally, note that I
need an & (ampersand) as the speech marks are also split over the two lines.
This looks trivial but there are plenty of traps when you are joining text within
quotes.
Microsoft\" _
& "Windows

Instructions

1. Copy and paste the script below into notepad.


2. Save the file with .vbs extension e.g. Welcome.vbs
3. Double click and then check the message box

You may like to run Regedit and navigate from the HKLM to the winlogon section

Export the Registry before you make any changes

' Welcome.vbs
' Example VBScript to write to the registry.
' Author Guy Thomas http://computerperformance.co.uk
' Version 1.4 - September 2005
' ----------------------------------------'
'
Option Explicit
Dim objShell
Dim strMessage, strWelcome, strWinLogon

' Set the string values


strWelcome = "Welcome" ' New Key
strMessage = "You are entering Guy's kingdom"
strWinLogon = "HKLM\SOFTWARE\Microsoft\" _
& "Windows NT\currentVersion\Winlogon\"

' Create the Shell object


Set objShell = CreateObject("WScript.Shell")

' These are the two crucial command in this script.


objShell.RegWrite strWinLogon & strWelcome, 1, "REG_SZ"
objShell.RegWrite strWinLogon & strWelcome, strMessage, "REG_SZ"

' I like a confirmation message


Wscript.Echo "Press Ctrl, Alt Del read top of Menu = " & strMessage

' The line below was purely for testing


' objShell.RegDelete strWinLogon & strWelcome
WScript.Quit

' End of script.

Learning Points
Note 1: Here is what creates the Welcome key: objShell.RegWrite strWinLogon
& strWelcome, 1, "REG_SZ".

Page 48 of 59
Introduction to VBScript.doc By Guy Thomas

Note 2: I found the commas a little tricky. Observe there is one comma after the
registry key (strWinLogon & strWelcome,) and another comma after the value
(1,).

Note 3: At first, my script failed because I omitted to put speech marks around
the "REG_SZ". This script needs a string value therefore we use "REG_SZ", other
registry scripts may require "REG_DWORD". My message is pay attention to
what the instructions say, DWORD or SZ.

Note 4: Trace the flow of the variables, strWinLogon, strWelcome and


strMessage.

Note 5: Perhaps it's just me, but whenever I script the registry, I make a
mistake with the path. For example, this script uses Microsoft\Windows NT\
section of the registry and not the Microsoft\Windows\ folder. My message is pay
attention to detail, especially if nothing happens and you need to correct the
script.

Note 6: Regedit is the utility for understanding and troubleshooting this script.
In particular, Regedit can ensure that you have the correct spelling, once you
locate the registry key, then go to File (Menu), Export. Now you are all set to
copy what ever is in the Selected Branch dialog box. Naturally, you paste this
registry string into your script.

Challenges
I have 'commented out' the line which uses .RegDelete. If you want a challenge,
then you could remove the apostrophe and thus remove entries from the
registry. However, I emphasise - be careful with .RegDelete. Make sure that you
do not delete the whole of Winlogon. Incidentally, if you do remove the '
comment and then run the script, at first you will see your strMessage, but when
you dismiss the WScript.Echo message box, the script will continue executing and
delete the strWelcome.

Ideally, I would like to add more exciting, but potentially dangerous settings to
the registry. If you feel that you have mastered this .RegWrite method, then I
am sure that you could research other keys to add to your registry.

From a pure scripting point of view, you could add extra (_) and see if the script
still runs as designed.

Summary - Scripting the Registry


If you need to add new keys and values to the registry, then VBscript is a great
solution. The key is to practice on innocuous settings just to master the
.RegWrite methods and syntax. Make sure that you export the registry before
you undertake major projects with .RegWrite.

Do not neglect the .RegRead method, as it can be the foundation of other scripts,
for example, scripts that test if Software has been installed on a machine.

This page covered the following VBScript methods, commands and


syntax:

.RegRead, .RegWrite, (.RegDelete), CreateObject("WScript.Shell"), Split, vbCr,


vbTab, (_) underscore.

Page 49 of 59
Introduction to VBScript.doc By Guy Thomas

Section 11 WMI Scripting - Memory

WMI (Windows Management Instrumentation)

Introduction to WMI
In earlier pages we met Logon Scripts, File System Objects and Active Directory
scripts. The WMI branch of the VBScript family has a different look and feel from
other members. Now, to appreciate the beauty of a jewel such as WMI, you
should view the crystal from different angles. To gain perspective and
understanding we will examine WMI from these five different angles:

1. See WMI as a method to automate the collection of hardware and software


data.
2. Regard WMI as a database holding information about computer disk,
services and processor and objects.
3. View WMI as a pipe connecting magically to the inner secrets of the
Microsoft operating system.
4. Approach WMI as a distinctive dialect of VBScript with its own WQL
vocabulary.
5. Treat WMI as a tool rather like a microscope to probe, and measure, the
operating system's properties.

When you think about it, the operating system knows everything!, Windows
Server 2003 must know how much memory each process is using, how much free
space there is on each partition, which devices are on which Bus. With WMI
scripting, you can query CIM library and view information about any aspect of the
operating sytem.

WMI Topics
Example 1 - Discover your Computer's Memory
WMI Tutorial - Learning Points
Example 2 - WMI Memory Script with an Input Box
Summary - WMI Memory

Example 1 - Discover your Computer's Memory


Here is a VBScript to discover how much Memory (TotalPhysicalMemory) there is
in a particular machine. What we need to do is interrogate the CIM (Common
Information Model) class called Win32_ComputerSystem. Calling for CIM is
rather like going to the library and asking the assistant to get books from the
archive. The first example examines the GetObject and ExecQuery, while the
second example script adds flexibility with an InputBox.

Prerequisites for your WMI Script


No specific requirements. This script should display the amount of memory on
any computer.

Page 50 of 59
Introduction to VBScript.doc By Guy Thomas

Instructions for Creating your Memory WMI Script

1. Copy and paste the example script below into notepad or a VBScript
editor.
2. Save the file with a .vbs extension, for example: Memory.vbs
3. Double click Memory.vbs and check the TotalPhysicalMemory (Memory).

Script to Discover how much Memory (RAM) is in your computer

' Memory.vbs
' Sample VBScript to discover how much memory in your computer
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.2 - September 2005
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objComputer, colComputer
Dim strLogonUser, strComputer

strComputer = "."

Set objWMIService = GetObject("winmgmts:" _


& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")

For Each objComputer in colComputer


Wscript.Echo "Computer Name: " & objComputer.Name _
& vbCr & "Total Memory " & objComputer.TotalPhysicalMemory
Next

WScript.Quit

' End of Memory WMI / VBScript

WMI Tutorial - Learning Points


From a WMI perspective

Note 1: We need to connect to the Root of the CIM namespace. The first
procedure is to tell winmgmts to access the root of the CIM library. Study this
line carefully as it crops up in so many WMI scripts :
Set objWMIService = GetObject("winmgmts:" & strComputer & "\root\cimv2")

Each of the above words is instructive, once again we create an object called
objWMIService. Observe how we tell GetObject that we want a "winmgmts:"
type of object, and not a shell or network object.

Note 2: In most WMI examples, we need security clearance to query the other
machine's hardware, this is why we add :
& "{impersonationLevel=impersonate}!\\" _

To begin with, just trust me and accept that WMI scripts usually need this
command to be sure that you have sufficient rights to query the operating
system.

Page 51 of 59
Introduction to VBScript.doc By Guy Thomas

Note 3: Set colComputer = objWMIService.ExecQuery _ Here we have a


standard VBScript phrase to prepare for the WQL command: "Select * from
Win32_ComputerSystem". The part of Win32 that we are particularly interested
in is _ComputerSystem. Win32 has dozens of possible properties, here we need
to query neither the disk nor processor, but we do want is the ComputerSystem
component.

From a VBScript perspective

Note 4: Even though there is only one computer, the script still needs the loop:
For Each....In... Next. Believe me, I tried to simplify the script by removing the
loop, but all I got was an 'Object required' 800xxxxx error.

Note 5: In this example, .TotalPhysicalMemory is the property that displays the


amount of RAM. However, in other examples we would substitute different
properties depending on our purpose, for example .NumberOfProcessors or
.SystemType.

Note 6: VBScript does not understand word-wrap, so if the command spans two
lines we add the _ (Underscore) at the end of the first line.

Example 2 - WMI Memory Script with an Input Box


This script builds on Example 1 and adds code for an inputbox. The result is
greater flexibility for you to point the the script to any machine on the network.
As a bonus, it includes a simple arithmetic routine to display the
TotalPhysicalMemory (RAM) in mb not bytes.

' MemoryInput.vbs
' VBScript with Input box, to discover how much RAM in computer
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.4 - September 2005
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objComputer, colComputer
Dim strLogonUser, strComputer, intRamMB

strComputer = "."
strComputer = InputBox("Enter Computer name", _
"Find Computer Memory", strComputer)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")

For Each objComputer in colComputer


intRamMB = int((objComputer.TotalPhysicalMemory) /1048576)+1
Wscript.Echo "System Name: " & objComputer.Name _
& vbCr & "Total Memory: " & intRamMB & " mb"
Next

WScript.Quit

' End of Sample Memory WMI / VBScript

Page 52 of 59
Introduction to VBScript.doc By Guy Thomas

WMI Tutorial - Learning Points


Note 1: The extra learning points in Example 2 concern VBScript rather than
WMI. Most example scripts use strComputer = ".", which refers to the current
machine. (The computer where you run the script.) By adding an Inputbox()
command, you can easily change the computer value to the NetBIOS name of any
machine on your network, at run time. Surprisingly, an IP address did not work,
it must be a machine name.

2) The other extra feature of this code is to perform a simple math calculation
and covert bytes to megabytes, which is a more meaningful unit of RAM memory.

Summary - WMI Memory


These WMI examples show you how to measure physical data such as
TotalPhysicalMemory (RAM). As you acquire VBScript skill, so you can tune up
your scripts with an inputbox. Once you have mastered one Win32 object, in this
case Win32_ComputerSystem.TotalPhysicalMemory, then you can apply the same
method to investigate objects such as disk or processor. Just amend the above
method by substituting Win32_PhysicalDisk or Win32_Processor.

This page covered the following VBScript methods, commands and


syntax:

Win32_ComputerSystem, GetObject("winmgmts:"...), InputBox()

Page 53 of 59
Introduction to VBScript.doc By Guy Thomas

Section 12 WMI Scripting - Chassis Type

WMI (Windows Management Instrumentation)

A WMI Script, which Employs Select Case to Discover Chassis Type


The practical point of this WMI script is to discover if the computer is a Mini
Tower, Desktop, Laptop or a Rack Mounted unit. While this is a fairly trivial task,
it frees up our minds to concentrate on the pure VBScript commands. View this
script as a vehicle to dissect and experiment with 'Select Case' and InputBox().

WMI Topics
Example - Discover your Computer's Type or 'Chassis Form'
WMI Tutorial - Learning Points
Summary - WMI Memory

Example - Discover your Computer's Type or 'Chassis Form'


This example employs WMI to interrogate the operating system for information
on the computer's chassis type. The VBScript portion of the script neatly
demonstrates the Select Case statement.

Prerequisites for your WMI Script


No specific requirements. This script should display the type or 'Form' of any
computer.

Instructions for Creating your 'Chassis Form' WMI Script

1. Copy and paste the example script below into notepad or a VBScript
editor.
2. Save the file with a .vbs extension, for example: ComputerChassis.vbs
3. Double click ComputerChassis.vbs and check the Computer's Chassis
Form.

Page 54 of 59
Introduction to VBScript.doc By Guy Thomas

Script to Discover your Computer's type or 'Chassis Form'

' ComputerChassis.vbs
' VBScript to discover the computer type or 'Chassis Form'
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.4 - September 2005
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objComputer, objChassis, objItem
Dim strComputer, strChassis, colChassis

strComputer = "."
strComputer = InputBox("Enter Computer name", _
"Find Computer Type", strComputer)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colChassis = objWMIService.ExecQuery _
("Select * from Win32_SystemEnclosure",,16)
For Each objChassis in colChassis
For Each objItem in objChassis.ChassisTypes
Select Case objItem
Case 1 strChassis = "Maybe Virtual Machine"
Case 2 strChassis = "??"
Case 3 strChassis = "Desktop"
Case 4 strChassis = "Thin Desktop"
Case 5 strChassis = "Pizza Box"
Case 6 strChassis = "Mini Tower"
Case 7 strChassis = "Full Tower"
Case 8 strChassis = "Portable"
Case 9 strChassis = "Laptop"
Case 10 strChassis = "Notebook"
Case 11 strChassis = "Hand Held"
Case 12 strChassis = "Docking Station"
Case 13 strChassis = "All in One"
Case 14 strChassis = "Sub Notebook"
Case 15 strChassis = "Space-Saving"
Case 16 strChassis = "Lunch Box"
Case 17 strChassis = "Main System Chassis"
Case 18 strChassis = "Lunch Box"
Case 19 strChassis = "SubChassis"
Case 20 strChassis = "Bus Expansion Chassis"
Case 21 strChassis = "Peripheral Chassis"
Case 22 strChassis = "Storage Chassis"
Case 23 strChassis = "Rack Mount Unit"
Case 24 strChassis = "Sealed-Case PC"

End Select
Next
Next
WScript.Echo "Your computer type is: " & strChassis
WScript.Quit

WMI Tutorial - Learning Points


From a VBScript perspective

Note 1: I am very fond of the, 'If.. Then...Else' construction, however it


becomes unwieldy after about the third 'else'. Then, one day, I discovered the
superior Select Case construction. Straightaway, I knew that Select Case would
be my salvation for scripts that dealt with multiple choices. My only difficulty is
remembering the correct sequence of those two words: Select Case.

Page 55 of 59
Introduction to VBScript.doc By Guy Thomas

From a WMI perspective

Note 2: We need to connect to the Root of the CIM namespace. The first
procedure tells winmgmts to access the root of the CIM library :
Set objWMIService = GetObject("winmgmts:" &
"{impersonationLevel=impersonate}!\\"
& strComputer & "\root\cimv2")

Note 3: In most WMI examples, we need security clearance to query a


machine's hardware, this is why we add :
& "{impersonationLevel=impersonate}!\\" _

To begin with, just trust me and accept that WMI scripts usually need this
command to be sure that you have the right to query the operating system.

Note 4: Set colComputer = objWMIService.ExecQuery _ Here is a standard


VBScript phrase to prepare for the WQL command: Select * from
Win32_SystemEnclosure". The part of Win32 that we are particularly interested
in is SystemEnclosure. Win32 has dozens of possible properties, here we need to
query the SystemEnclosure collation of properties.

Summary - WMI
This WMI example shows you how to interrogate the operating system and
discover information about the computer's Chassis type. As you acquire VBScript
skill, so you can tune up your scripts with an inputbox. Once you have mastered
one Win32 object then you can apply the method to investigate objects such as
Win32_PhysicalDisk or Win32_Processor.

This page covered the following VBScript methods, commands and


syntax:

Win32_SystemEnclosure, For Each... Next, Case Select, GetObject("winmgmts:" )

Page 56 of 59
Introduction to VBScript.doc By Guy Thomas

Index for Introduction to VBScript

Who is this Introduction to VBScript ebook aimed at? .......................................................... 1


Introduction to VBScript by Guy Thomas .................................................... 2
Simple, yet powerful VBScripts ............................................................................................. 2
Introduction to VBScript......................................................................................................... 2
Tasks for VBScript............................................................................................................. 2
VBScript Methods, Commands & Syntax.......................................................................... 2
Section 0 Introduction to VBScript................................................................... 3
Introduction - What are the Benefits of Learning VBscript? .............................................. 3
Skills (Multi-Skills) ............................................................................................................. 3
Secrets of Scripting ........................................................................................................... 4
Section 1 VBScript - Check Version ............................................................ 5
Introduction to Checking Version Numbers ...................................................................... 5
Topics for Checking Version Numbers.............................................................................. 5
Example 1 - VBScript to Check the WSH Version ............................................................ 5
Prerequisites ..................................................................................................................... 5
Sample VBScript to Check the WSH Version ................................................................... 6
Learning Points ................................................................................................................. 6
Example 2 - VBScript to Check the WSH Version and Build Number .............................. 7
Learning Points ................................................................................................................. 7
Example 3 - VBScript to Check the VBScript Version ...................................................... 7
Sample Script to Check the VBScript Version .................................................................. 8
Learning Points ................................................................................................................. 8
Challenge: ......................................................................................................................... 8
Summary of Checking Version Numbers .......................................................................... 8
Section 2 VBScript - Variables..................................................................... 9
Introduction to VBScript Variables......................................................................................... 9
Topics for Variables........................................................................................................... 9
What is a VBScript Variable? ............................................................................................ 9
Example 1 - Using a String Variable ............................................................................... 10
Learning Points ............................................................................................................... 10
Example 2 - Using a Variable to Increment a Loop. ....................................................... 11
The Hungarian Variable Convention ............................................................................... 12
Hungarian Convention Example: .................................................................................... 13
Learning Points ............................................................................................................... 13
Summary of VBScript Variables...................................................................................... 13
Section 3 Create an OU (Organizational Unit) in Active Directory.............. 14
Tutorial for Creating an OU (Organizational Unit) with VBScript......................................... 14
Topics for Creating an OU (Organizational Unit) with VBScript...................................... 14
Our Mission and Goal...................................................................................................... 14
Example 1 - Create a Top Level OU ............................................................................... 14
Learning Points - Binding to Active Directory ...................................................................... 16
Learning Points - Creating the actual OU ....................................................................... 17
Example 2 - Create a Child OU....................................................................................... 18
Learning Points - Creating the Child OU ............................................................................. 19
Example 3 - Adding error-correcting Code ..................................................................... 19
Summary Creating an OU ................................................................................................... 20
Section 4 Create a User in Active Directory ............................................... 21
Introduction to Create a User in Active Directory............................................................ 21
Tutorial for Creating a User Account with VBScript............................................................. 21
Topics for Creating a User Account with VBScript.......................................................... 21
Our Mission and Goal...................................................................................................... 21
Example 1 - Script to Create a User in Active Directory ................................................. 22
Prerequisites ................................................................................................................... 22
Script to Create a User in a Named OU (Organizational Unit) ....................................... 22
VBScript Tutorial - Learning Points ................................................................................. 23
Example 2: Script to Create a User in a Named OU (Organizational Unit) .................... 24

Page 57 of 59
Introduction to VBScript.doc By Guy Thomas

VBScript Tutorial - Learning Points ................................................................................. 24


Summary of Creating User Accounts.............................................................................. 25
Section 5 Map Network Drive .................................................................... 26
Introduction to MapNetworkDrive.................................................................................... 26
Topics for MapNetworkDrive........................................................................................... 26
Our Mission and Goal...................................................................................................... 26
Example - MapNetworkDrive VBScript Method .............................................................. 27
Learning Points for MapNetworkDrive................................................................................. 27
Guy's Challenges ............................................................................................................ 28
Summary of MapNetworkDrive ....................................................................................... 28
Section 6 Map a Network Printer................................................................ 29
Introduction to AddWindowsPrinterConnection Logon Script ............................................. 29
Topics for AddWindowsPrinterConnection Scripts ......................................................... 29
Our Mission ..................................................................................................................... 29
Example 1 - Simple Printer Script with AddWindowsPrinterConnection......................... 29
Learning Points.................................................................................................................... 30
Example 2 - Printer Script with AddWindowsPrinterConnection..................................... 31
Example 2 - Printer Script with AddWindowsPrinterConnection..................................... 31
Learning Points.................................................................................................................... 31
Example 3 - SetDefaultPrinter......................................................................................... 31
Learning Points.................................................................................................................... 32
Summary of AddWindowsPrinterConnection.................................................................. 32
Section 7 Create a Folder (Stage 1 of 3).................................................... 33
Introduction to Create Folders......................................................................................... 33
Topics for VBScript.......................................................................................................... 33
Meet the VBScript terms ................................................................................................. 33
Example 1 - Basic VBScript to Create a Folder .............................................................. 34
Prerequisites ................................................................................................................... 34
Sample Script to Create a Folder.................................................................................... 34
VBScript Tutorial - Learning Points ................................................................................. 35
Example 2 - Create a Folder with error-correcting Code ................................................ 35
Example 3 - Script to Create a Folder, then Open Windows Explorer............................ 35
VBScript Tutorial - Learning Points ................................................................................. 36
Summary of Creating Folders ......................................................................................... 36
Section 8 Create a Text File (Stage 2 of 3)................................................ 37
A VBScript Tutorial for Creating a File ................................................................................ 37
Topics for Writing or Appending to a File with VBScript ................................................. 37
Our Mission and Goal...................................................................................................... 37
Example 1 - Basic VBScript to Create a File with CreateTextFile .................................. 37
Prerequisites ................................................................................................................... 37
Sample Script to Create a File ........................................................................................ 38
VBScript Tutorial - Learning Points ................................................................................. 38
Example 2 - Create a File with error-correcting Code..................................................... 39
Sample Script to Create a File and Check if a File Already Exists ................................. 39
VBScript Tutorial - Learning Points ................................................................................. 40
Summary of Creating Files.............................................................................................. 40
Section 9 Append Data to Text File (Stage 3 of 3)..................................... 41
A VBScript Tutorial for Writing or Appending to a File ........................................................ 41
Topics for Writing or Appending to a File with VBScript ................................................. 41
Our Mission and Goal...................................................................................................... 41
Example - VBScript to Append Text to a File.................................................................. 41
Prerequisites ................................................................................................................... 42
Sample Script to Append Text to a File........................................................................... 43
VBScript Tutorial - Learning Points ................................................................................. 44
Summary of How to Append Data to a Text File............................................................. 44
Section 10 Registry Scripting ................................................................... 45
Introduction Registry Scripting............................................................................................. 45
Topics for Registry Scripting ........................................................................................... 45
Mission to Read the Registry .......................................................................................... 45

Page 58 of 59
Introduction to VBScript.doc By Guy Thomas

Example 1 - To Extract Windows Version Information from the Registry ....................... 45


Learning Points.................................................................................................................... 46
Challenges........................................................................................................................... 47
Summary - Reading the Registry ........................................................................................ 47
Mission to Write Keys to the Registry ............................................................................. 47
Example 2 - To Write Information into the Registry ........................................................ 47
Learning Points.................................................................................................................... 48
Challenges........................................................................................................................... 49
Summary - Scripting the Registry........................................................................................ 49
Section 11 WMI Scripting - Memory .......................................................... 50
Introduction to WMI ............................................................................................................. 50
WMI Topics ..................................................................................................................... 50
Example 1 - Discover your Computer's Memory............................................................. 50
Prerequisites for your WMI Script ................................................................................... 50
Script to Discover how much Memory (RAM) is in your computer ................................. 51
WMI Tutorial - Learning Points........................................................................................ 51
Example 2 - WMI Memory Script with an Input Box........................................................ 52
WMI Tutorial - Learning Points........................................................................................ 53
Summary - WMI Memory ................................................................................................ 53
Section 12 WMI Scripting - Chassis Type ................................................. 54
A WMI Script, which Employs Select Case to Discover Chassis Type ............................... 54
WMI Topics ..................................................................................................................... 54
Example - Discover your Computer's Type or 'Chassis Form'........................................ 54
Prerequisites for your WMI Script ................................................................................... 54
Script to Discover your Computer's type or 'Chassis Form'............................................ 55
WMI Tutorial - Learning Points........................................................................................ 55
Summary - WMI .............................................................................................................. 56
Index for Introduction to VBScript........................................................................................ 57

Page 59 of 59
This document was created with Win2PDF available at http://www.daneprairie.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.

You might also like