Introduction To VBScript
Introduction To VBScript
Table of Contents
Page 1 of 59
Introduction to VBScript.doc By Guy Thomas
Introduction to VBScript
by Guy Thomas
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.
Page 2 of 59
Introduction to VBScript.doc By Guy Thomas
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.
Examples
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.
Page 4 of 59
Introduction to VBScript.doc By Guy Thomas
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.
Prerequisites
This is a script that will execute equally well on a Windows server or an XP
machine.
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
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
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.
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
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.
Page 8 of 59
Introduction to VBScript.doc By Guy Thomas
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.
Page 9 of 59
Introduction to VBScript.doc By Guy Thomas
Prerequisites
Instructions
' 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"))
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.
Page 10 of 59
Introduction to VBScript.doc By Guy Thomas
' 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"
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 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
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.
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
' 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"
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.
String Variables, Number Variables, Object Variables, also For .... Next (Loop)
and .Create("Computer...")
Page 13 of 59
Introduction to VBScript.doc By Guy Thomas
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.
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
' 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"
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 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.
strContainer ="OU=Accounts"
Note 1: Guy loves variables, so here is the name of the variable which holds the
OU name:
strContainer ="OU=Accounts"
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
Creating a child OU is simple but there is a classic trap. Which of these two
sequences should you use?
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.)
Page 18 of 59
Introduction to VBScript.doc By Guy Thomas
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().
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)
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.
Page 20 of 59
Introduction to VBScript.doc By Guy Thomas
Page 21 of 59
Introduction to VBScript.doc By Guy Thomas
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.
WScript.Quit
Page 22 of 59
Introduction to VBScript.doc By Guy Thomas
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
Create a new OU. I called my OU Accounts, what name will you choose?
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
WScript.Quit
Page 24 of 59
Introduction to VBScript.doc By Guy Thomas
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.
Page 25 of 59
Introduction to VBScript.doc By Guy Thomas
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.
MapNetworkDrive Method
Page 26 of 59
Introduction to VBScript.doc By Guy Thomas
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
'
' 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"
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.
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.
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.
Page 28 of 59
Introduction to VBScript.doc By Guy Thomas
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.
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
'
' 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.
Page 30 of 59
Introduction to VBScript.doc By Guy Thomas
WScript.Quit
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.
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
'
' 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
WScript.Quit
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.
Page 32 of 59
Introduction to VBScript.doc By Guy Thomas
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.
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
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.
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.
' 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")
Page 34 of 59
Introduction to VBScript.doc By Guy Thomas
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:
' 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"
WScript.Quit
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"
WScript.Quit
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.
Page 36 of 59
Introduction to VBScript.doc By Guy Thomas
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
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.
' 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"
Wscript.Quit
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
' 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"
' 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
Page 39 of 59
Introduction to VBScript.doc By Guy Thomas
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.
Page 40 of 59
Introduction to VBScript.doc By Guy Thomas
3) Appending data (as in leaving the existing text and adding more).
Page 41 of 59
Introduction to VBScript.doc By Guy Thomas
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.
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
' 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"
WScript.Quit
Page 43 of 59
Introduction to VBScript.doc By Guy Thomas
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
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.
Page 44 of 59
Introduction to VBScript.doc By Guy Thomas
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.
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\"
Wscript.Echo "Operating System " & vbTab & strOS & vbCr _
& arrOS(1) & " version " & vbTab & strVersion & vbCr _
& "Service Pack " & vbTab & strSP
WScript.Quit
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 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.
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.
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
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
You may like to run Regedit and navigate from the HKLM to the winlogon section
' 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
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 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.
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.
Page 49 of 59
Introduction to VBScript.doc By Guy Thomas
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:
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
Page 50 of 59
Introduction to VBScript.doc By Guy Thomas
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).
' 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 = "."
WScript.Quit
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 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 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.
' 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")
WScript.Quit
Page 52 of 59
Introduction to VBScript.doc By Guy Thomas
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.
Page 53 of 59
Introduction to VBScript.doc By Guy Thomas
WMI Topics
Example - Discover your Computer's Type or 'Chassis Form'
WMI Tutorial - Learning Points
Summary - WMI Memory
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
' 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
Page 55 of 59
Introduction to VBScript.doc By Guy Thomas
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")
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.
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.
Page 56 of 59
Introduction to VBScript.doc By Guy Thomas
Page 57 of 59
Introduction to VBScript.doc By Guy Thomas
Page 58 of 59
Introduction to VBScript.doc By Guy Thomas
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.