Académique Documents
Professionnel Documents
Culture Documents
VBScripting Basics
Part I: Getting Started with Visual Basic (VB) Scripting
SUPER-GEEK, STEP I—OR, GETTING TO THE MOUNTAIN
Rod Trent
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
M uch of your life, you’ve felt just a little bit off-center. Your friends
and co-workers have noticed it, too. Whether it was their issuances
of “Geek-boy” in hushed tones, or their smattering of verbal
applause when you solved something no one had been able to
before, you’ve felt that there was something more for you in life – something
only the gods could have ordained.
Not only that, just when you thought you were getting much closer to being
accepted in social circles (hmmm…or maybe it’s just that you are being
tolerated because they now NEED you), Windows Script Host entered your life.
You can’t quite put your finger on the feeling, but it’s as if destiny has arrived.
Windows Script Host is the key you’ve been looking for. Like a burning ember
on a mountain in view, fulfillment and redemption are just a hardened climb
away.
In this book, you’ll take the first steps toward that burning ember, by
understanding what Windows Script Host really is and how to get help with the
language, by learning what a powerful scripting language is before you and
how you can get to the base of that mountain.
This book centers on the most frequently asked questions (FAQs) that
individuals pose when they are just embarking on their scripting journey. To
date, the Internet has resources littered about that contain the best answers
when starting out for the scripting prize. This book serves to centralize those
great answers, so you can just “dig in” instead of searching the vast World
Wide Web to try to pacify your curiosity.
Myself, I’m a social outcast. To me, following rules like that is too much effort.
I’d rather have the knowledge beforehand that would enable me to interact
intelligently.
If you’re like me (and I suspect you are, since you’re reading this book), you
like to have all the information up-front. A tidbit of knowledge at a Geek
conference can be debilitating, and Geeks don’t laugh silently. They laugh right
to your face and laugh so loud that the entire room shifts their attention to
your location. If you’re lucky, the jolly accuser has set down his can of
Mountain Dew just before going off on you.
This is why, understanding what Windows Script Host is can be both self-
rewarding and completely necessary before heading out to the local technology
fest.
Windows Script Host (WSH) is an installable component that hosts Windows
scripting functions. It allows Windows computers to run scripts written in the
Visual Basic (VB) Scripting and JavaScript languages. Said in plainer terms,
WSH is the brains behind the brawn. It’s the horse to the cart; the footman to
the rickshaw; the feet to the Flintstone-mobile—you get the picture.
When you throw a VB script at a Windows computer and WSH is not installed,
the computer can’t react. You may have the most glorious VB script, worthy of
a year’s salary at least, but unless WSH is installed on the computer, the script
falls flat.
This leads us to the next frequently asked question in the journey toward
Geekdom.
2
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
EXTRA NOTE: For those too young or too cool to remember MacGyver, look at
this link: http://www.jumptheshark.com/m/macgyver.htm.
As amazing as that show was (groan), WSH is very much the MacGyver of the
Windows computing environment. A better question might be, “What can’t I do
with WSH?” WSH is ideal for logon scripting, administrative scripting, and
machine automation. You’ll understand further just how powerful WSH is as
you read through the rest of the book, but here’s a small sample.
With WSH you can:
NOTE: At the time of this writing, the latest version of WSH is version 5.6,
which you can download from http://msdn.microsoft.com/scripting. Microsoft
can, without warning, change the location of the content on their website, but
this specific link has been safe for a couple years.
3
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Okay, to better answer which version of WSH you need, let’s just say it’s best
to have the latest and greatest version. Why? Well, not only do subsequent
versions address bug fixes, they also offer new features of which you can take
advantage. In addition, you can still utilize the features you are already used
to, because the current version is backward compatible – meaning you are not
going to lose functionality at all. You are just adding new and exciting features
to your ever-growing Geek Toolkit.
TIP: There are specific downloads for the different versions of Windows. For
example, there is one download for Windows 2000 and others just for Windows
NT, 98, and ME. Make sure you use the correct download for the target
platform. Windows XP already has the most current version of WSH installed as
part of the operating system load.
4
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
The installation has a few options for controlling how it performs, as shown in
Figure 1 below.
EXTRA NOTE: Per Figure 1, running the installation with the /Q switch will
cause WSH 5.6 to install quietly.
Installing the WSH upgrade, even with the /Q switch, will require the computer
to reboot to finish the installation on the next boot. Remember when I said
vendors now include all hidden switch functions in the /? command? Well,
there are still some exceptions to the rule. If it is your task to deploy the WSH
upgrade to a multitude of computers during the workday, the end-user will
probably get upset if they have to close all of their applications and reboot the
computer. Even though the installation Help screen in Figure 1 doesn’t show a
command-line option to tell the installation not to prompt to reboot when
finished, there is a command option to accomplish this. Running the following
command-line will cause WSH to install silently and to suppress any reboot
message: scr56en.exe /q:a /r:n
Note that this command does not mean that the computer doesn’t still need to
be rebooted at some point. In fact, for the installation to finish completely, the
computer will need to be restarted, and you can notify the end-users to do this
at their leisure. The WSH upgrade attempts to overwrite files during the
installation process. If some of these files are in-use during the install (and
they will be), they are flagged to be replaced during the computer boot
process. In effect, the new version of WSH will not work until the computer’s
memory is flushed through a reboot.
Then, why aren’t these additional switches readily available in the installation
Help screen? That’s a very good question—one that I myself will ask when I
can pinpoint the correct person. Until then, the following table (Table 1)
5
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
represents the known switches for Microsoft patch installations. Your mileage
may vary.
Switch Definition
/r:n Never restart—do not restart the computer even if it is necessary to complete
the installation
/r:s Silent restart—automatically restart the computer without prompting the user
/s Silent mode—some programs use this switch instead of the /q switch to install
in quiet mode
6
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
Also, included in the documentation at the noted link is a full list of the
enhancements Microsoft included in version 5.6. Then again, why should you
immediately jump out to a webpage to read a document when you’re totally
engrossed in this book? There’s no need. Here’s a brief overview of the new
features:
Security
If you read the trade-rags very often, you can’t turn too many pages without a
security article jumping out at you. Security is THE hottest topic in the IT
industry at the present—and rightly so. .VBS and .VBE files have had their day
in the sun as potentially dangerous email parasites. Without special caution,
they could rear their ugly heads once again. When you think about it, anyone
who can become even remotely adept at writing VB scripts could be considered
a dangerous person. The VB scripting language is so powerful that there’s very
little you can’t do with it. What a person does with the power is up to them.
Some turn to “the dark side” and write scripts that can damage data. Whether
it starts as a practical joke or just a dreadfully devious person bent on the
destruction of mankind, using VB scripting knowledge for anything but good is,
well . . . just bad.
With the release of WSH 5.6, Microsoft included some critical configuration
parameters in the form of registry key values. By modifying these registry
values, you can beef up security for the scripting engines installed on your
company computers. Browse through Table 2 below for full understanding of
your configuration options. Each of these registry values can be found in both
HKLM\Software\Microsoft\Windows Script Host\Settings and
HKCU\Software\Microsoft\Windows Script Host\Settings.
Remote If 1, then this machine may run scripts remotely. If 0, it may not.
Default is 0 if not present.
7
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
scripts will display a prompt, warning the user that they are about
to do something dangerous and giving them a chance to back
out. If 2, then only trusted, signed scripts will be allowed to run.
On WinXP, you also have the option of using the SRPs—see
UseWINSAFER below. Default is 0 if not present.
LogSecuritySuccesses If 1, then all security failures are entered in the event log. Security
failures include trying to run when Enabled = 0, trying to run
remotely when Remote = 0, attempting to run an untrusted script
when TrustPolicy = 2, etc. Default is 1 if not present.
Table 2 – WSH Security Registry Settings
In addition to these security configuration options, script users can now verify
the authenticity of a script before running it; script developers can sign their
scripts to prevent unauthorized modifications; and administrators can enforce
strict policies that determine which users have privileges to run scripts locally
or remotely.
Argument Handling
Handling and documenting command line arguments is simpler. The process of
integrating your scripts with other command line scripts has been simplified,
and it is easier to create scripts that can supply the user with help information.
8
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
Processes as Objects
You determine the status of spawned processes and access their standard I/O
streams.
9
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Let’s take a look at a simple script. This script, written for CScript.exe, prompts
you for a specific computer name in a nice Windows box, as shown in Figure 2.
It then connects to the computer you specified, retrieves service information,
and then displays the output in a DOS window, as shown in Figure 3.
10
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
When you look again at the information shown in Figure 2, you can see a long
list of information. This output is actually a multitude of pages long, which
causes the display in the DOS window to scroll for almost 30 seconds. If you
happened to run this script with WScript.exe, a window would display for EACH
line you see in the figure. In addition, since the output is an enormous amount
of information, you would see a new window pop up for EVERY new line, such
as the window shown in Figure 4. If you calculate the number of services that
can be installed on any given computer, multiplied by the number of output
lines for each service as defined in the script, that’s almost 800 windows
popping up in your face every one to two seconds. The worst part . . . you
have to hit the OK button on each Window before the script will advance.
11
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Unless you’re a psychotic person or someone with a lot of time to spare, you
will agree that this is time consuming and needless. If you somehow get duped
into running a script with WScript.exe that was meant to be run with
CScript.exe, there’s an easy way to break out of the seemingly endless loop.
Both engines run as Windows processes. Shown in Figure 5, executing
Windows Task Manager and choosing the Processes tab, you only need to
search the list for the running engine, highlight it, and click the End Process
button to exit your worst scripting nightmare.
If you wanted to actually run the script with WScript.exe to see the pretty
windows, instead of the output in the drab DOS window, you would only need
to rewrite the WScript.Echo section. You would want to use the MsgBox
method instead of using the Echo method. It would look something like the
following script:
12
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
You’d probably even want to go a bit further, because you would still expect to
see one window for every installed service. While this minimizes your headache
somewhat, it doesn’t cure it. The best method is to pipe the output to a text
file, so you can review the contents at your leisure, either on-screen or printed
on a piece of paper.
Don’t worry, this doesn’t have to be a permanent change! Once you change it,
you’re not stuck with it for your entire scripting life. Like Superman in the
13
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Bizzarro world, the default engine-changing command has an alter ego. You
can always change it back, using the following reversal command-line:
cscript//h:wscript
Ah . . . so then, there are command-line options for the scripting engines? No,
I’m not holding out on you. There are more command-line options for both
CScript.exe and WScript.exe. I cover those in the next section.
14
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
You’ll notice, by looking between Figures 5 and 6, that there is only one
difference in the command-line options: the //U switch used with CScript.exe.
15
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
NOTE: We have written this book for those individuals who want to add
scripting to their IT tool belt, to be used as a way to increase their skill-set and
to provide more value for their company and employment. Since, we won’t be
discussing web development, the scripts and script discussions in this book
will be targeted at the VBScript language.
Both scripting languages are very similar to the counter-parts after which they
are named. There’s very little difference between the full-blown programming
language and the light-weight scripting language. “VB Jr.” and “Java Jr.” have
many of the same functions that their Big Brothers have available. The major
difference is that scripting languages cannot be compiled and run as stand-
alone applications – meaning you still need WSH installed to host the script. An
application written using a full programming language doesn’t need a host; it
can run on its own on the computer and operating system it was written for.
However, you can “encode” a script. See the next FAQ for details.
16
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
Encode.vbs
Option Explicit
Dim fso
Set fso = WScript.CreateObject(“Scripting.FilesystemObject”)
Dim argv
Set argv = WScript.Arguments
Dim SourcePath
SourcePath = argv(0)
If SourcePath = “” Then WScript.Quit
Dim szExt, bstrScript, destExt
Select Case fso.GetExtensionName(SourcePath)
Case “vbs”
szExt = “.vbs”
bstrScript = “VBScript”
destExt = “.vbe”
Case “js”
szExt = “.js”
bstrScript = “JScript”
destExt = “.jse”
Case Else
MsgBox fso.GetExtensionName(SourcePath) & “ files not supported
in this script.”
WScript.Quit
End Select
Dim bstrStreamIn
bstrStreamIn = fso.OpenTextFile(SourcePath, 1).ReadAll
Dim enc, EncodedText
Set enc = WScript.CreateObject(“Scripting.Encoder”)
EncodedText = enc.EncodeScriptFile(szExt, bstrStreamIn, 0,
bstrScript)
Set enc = Nothing
Dim DestPath
DestPath = Replace(SourcePath, szExt, destExt)
If Not fso.FileExists(DestPath) Then
Dim DestFile
17
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Alternatively, whatever can be encoded can be decoded with the right utility or
script. There is a freeware decoder utility available for download at the
following link: http://www.virtualconspiracy.com/scrdec.html, and some code
to learn how to create your own decoder here: http://www.planet-source-
code.com/xq/ASP/txtCodeId.6532/lngWId.4/qx/vb/scripts/ShowCode.htm.
18
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
When you’ve had your fill of Microsoft’s documentation, then what? The
Internet is such an enormous place. Surely there are some websites I can give
you to go on your scripting shopping spree. Well, here they are:
à MyITforum.com—http://www.myITforum.com
19
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
20
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
anything is. It is now more likely that a wasp will sting you, than a Windows
script will “infect” your computer. With all of the tools available to minimize
your vulnerabilities, you are as safe as you want to be. These days, if a virus
infects your machine, it’s probably your own fault. Inserting old diskettes into
your disk drive, reading your email archives that date back to the dawn of the
Internet, or not applying the latest Anti-virus patches—you can only blame
yourself.
You can even further minimize your vulnerability to running unsafe or
untrustworthy Windows scripts by making a simple change to the Windows
registry. Associate all Windows scripts with Notepad, so that when a script is
double-clicked or executed, it opens in the text editor, instead of running as a
script. You can still run the script as a script by initiating the execution of the
script, using the appropriate WSH engine.
For example, instead of just running encode.vbs from a command-line, run
CScript.exe encode.vbs. This is a manual way of telling WSH that it needs to
do something. Windows scripts are no longer “allowed” to run unassisted. You
have to tell WSH which script engine to use. This will save you some sleepless
nights worrying that an end-user may be poking around in his computer files
and double-clicking on a script to remove access to the entire computer.
The registry modification:
Hive: HKEY_Classes_Root
1. Key = JSEFile\Shell o New Value = Edit
o New Value = Edit 5. Key = WSFFile\Shell
2. Key = JSFile\Shell o New Value = Edit
o New Value = Edit 6. Key = WSHFile\Shell
3. Key = VBSFile\Shell o New Value = Edit
o New Value = Edit 7. Key = WSHFile\Shell\Edit\command
4. Key = VBEFile\Shell o New Value =
C:\WINNT\System32\Notepad.exe %1
NOTE: You’ll notice that the location to Notepad.exe is listed as
C:\WINNT\System32, which is the directory fro Windows NT, Windows
2000, and Windows XP. You’ll need to modify that value if you want to
protect Windows 95, Windows 98, and Windows ME computers. Notepad.exe is
normally stored in the C:\Windows directory on these computers, but you had
better check to make sure.
21
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Notepad
To open or edit a script in Notepad, you only need to right-click on the script,
and choose Edit. By performing this action, I opened the Encode.vbs script
pasted earlier in the chapter, shown in Figure 9.
Notepad is the best tool to start with, and it helps reorganize your mind to be
more in tune with the styles and formatting associated with VB scripting. After
a few weeks of coding, you’ll start dreaming in all black-and-white text.
Notepad has some of the same features you’ll find in other script editing tools.
You can Edit | Find specific text, and replace it with your own text. You can
22
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
also skip to a specific line number. This extremely important feature needs to
be present in any script editor to which you eventually switch. Why? When you
start coding you’ll understand better, but when your code is not quite right,
and you attempt to run your script, an error message will display, giving you
the line number where the error occurred (similar to the error message shown
in Figure 10).
1. With Word Wrap turned off (the Go to Line command will not work
when Word Wrap is enabled. You disable it by un-checking Word
Wrap under Notepad’s Format menu.), hit Ctrl-G on your keyboard.
You’ll be presented with the pop-up screen shown in Figure 11.
2. Just type in the offending line number, and Notepad whisks you to the
appropriate line straightaway.
23
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
I really couldn’t live without this great feature, and you’ll quickly find you feel
the same. I can’t think of a single script I’ve written where I didn’t have to
“tweak” it a bit before it would work properly, and having the Go to Line
command available is a time-saver.
ConTEXT
I couldn’t finish off this FAQ without giving you at least a couple alternatives to
Notepad. I search periodically to see if anyone has developed a new tool for
creating and editing VB scripts. On one of my searches, I found ConTEXT
(http://www.fixedsys.com/context/). ConTEXT is a general-purpose
programmer’s editor, allowing you to work with more than just VB scripts.
Shown in Figure 12, ConTEXT is a nice editing tool with a great interface.
ConTEXT not only colorizes the functions of your code for easy recognition and
includes the adored Go to Line function, but it also has a very handy Macro
feature, giving you the ability to record repetitive tasks. Instead of hand typing
a section of code you use often, you can record it once and only need to
choose to use it later on. Neat!
24
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
ConTEXT is a freeware application. All it will cost you is a little bandwidth for
downloading the 1.03 MB file. I guess you could say it costs just a tad bit more
than Notepad. When you’re ready to move on to another scripting or
programming language, ConTEXT fits the bill, as there are “highlighter” add-
ons for a wide number of additional languages. These highlighter add-ons tell
ConTEXT how to handle the colorization of other programming languages. You
can download them all or download the specific highlighter for the job. The
current list includes:
WMI Scriptomatic
One last recent entry to the school of automated utilities is the WMI
Scriptomatic utility. I couldn’t finish this FAQ without making mention of this
great script. Yes, you heard me correctly. This utility is in fact, another great
script, which you can modify to meet your needs. In fact, someone recently
modified the WMI Scriptomatic script to connect to a Microsoft Systems
Management Server and retrieve information from there. You can find and
download this modified script, by going to the myITforum.com search engine
(http://www.myitforum.com/search.asp) and searching for the keyword
scriptomatic.
The WMI Scriptomatic is an example of a hypertext application, essentially a
Web page that uses a .hta file extension. When executed, this script connects
to the local computer’s WMI repository (a database full of information about
the computer) and then presents you with all of the values it finds. Choosing a
value, the WMI Scriptomatic utility will automatically generate the VB script
you need to use to pull the information from the WMI repository yourself.
How’s that for writing your first scripts?
Figure 13 shows the WMI Scriptomatic utility being used to build a script to pull
information about the computer’s serial port hardware. From the interface, you
25
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
can Save the script or Run the script, all without leaving the comfort of the
GUI.
Figure 13: WMI Scriptomatic Utility Creating Script for Serial Port Information
NOTE: For the best information on WMI and WMI scripting, pick up the book,
WMI Essentials for Automating Windows Management, by Marcin Policht.
26
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
Login Scripts
Any company that has a network managed through a domain potentially
utilizes login scripts. Login scripts allow network administrators to send
instructions to the remote computer each time it logs onto the network. VB
scripts work great when inserted into login scripts and make an excellent
solution for making sure the scripts run on every computer in the organization.
Some companies have even replaced their login scripts completely with VB
scripts! OK, that’s just crazy, you say. Granted, some extreme knowledge of
VB scripting is required, but it can be done and easily. If you remember how
powerful VB script is, it may make better sense, realizing that if you have
replaced your login scripts with VB scripts, you can utilize that power anytime
you want, instead of searching the Internet for a freeware tool that will work in
your environment.
Dim net
Set net = CreateObject("WScript.Network")
Network Share
VB script works like any other application or program that executes on a local
computer, so it’s not surprising that you can place a VB script on a network
share that users have access to and have them run the script in some way.
Just plop the script on the network, and offer a link to run the script. You can
offer the link through an email, a login script, or some other method you
27
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
personally utilize to get software to the end-user. VB scripts work just fine
using a hard-coded drive letter or a UNC path.
Web Page
More and more companies utilize some kind of internal website for offering
company information. Some go even farther by providing software downloads
and installations. Websites are a great tool for company communications.
VB scripts run great from web pages—either through a link that executes the
script, or a component that runs the script when a specific web page is loaded
into the computer’s web browser.
usage: psexec \\computer [-u username [-p password]] [-s] [-i] [-c
[-f]] [-d] program [arguments]
-p Specifies optional password for user name—if you omit this you will be prompted
28
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
-i Run the program so that it interacts with the desktop on the remote system.
-c Copy the specified program to the remote system for execution. If you omit this
option, then the application must be in the system's path on the remote system.
-f Copy the specified program to the remote system, even if the file already exists
on the remote system.
-d Don't wait for application to terminate. Only use this option for non-interactive
applications.
arguments Arguments to pass—note that file paths must be absolute paths on the target
system.
You can download PsExec from the following location on SysInternals’ website:
http://www.sysinternals.com/ntw2k/freeware/psexec.shtml.
Remote WSH
With the remote execution utilities on the market, you didn’t think Microsoft
would sit idly back and not supply this functionality in WSH, did you? Not likely.
If it’s a good, sound technology you can expect Microsoft to incorporate it
eventually.
Remote WSH is a new technology included in WSH 5.6. It provides the ability
to run a script on a remote machine or machines. With Remote WSH, the script
is physically copied from the local machine to the remote machine before
executing. In order to enable Remote WSH functionality, you must first set up
the remote machine with the proper security settings.
NOTE: Both the remote and local machines must be running Windows NT 4
SP3 or greater in order to use Remote WSH.
29
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
30
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
this: “Can we do it? YES WE CAN!” And, you don’t need to set up Remote WSH
to do it.
Much like an application can query a SQL database for data, you can utilize VB
scripts to connect to a remote computer and pull information about that
computer. Each computer stores a significant amount of data about itself. This
data is stored in the WMI repository. The WMI repository works similarly to an
SQL database, except the WMI repository is filled with data automatically.
There are lots of administrators who aren’t aware of the data contained on a
computer, so don’t feel bad if you’re just hearing about this. Don’t worry – you
won’t be kicked out of the Geek club and marked for life with the word “End-
User” stamped on your forehead.
WMI, which stands for Windows Management Instrumentation, is a computer
data storehouse accessed easily with VBScript. The WMI database structure is
broken down into Classes with Properties full of data. For example, there’s a
Computer class (Win32_ComputerSystem) which stores information
(Properties) about the local computer, such as the Current Time Zone, the
Manufacturer of the computer, and the Domain that the computer belongs to.
Believe it or not, you can also query this database for the computer’s actual
serial number! Can you even idealize how important that is?!! You only need to
know a special connection string—the Geek-to-Computer handshake.
The following “handshake” connects to the computer BIOS class on a remote
computer, allowing you to get information about the installed BIOS options
(which, incidentally, contains the serial number of the computer). To make it
simple, the script first prompts you for the name of the computer from which
you want to extract the serial number.
31
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
winmgmt1 = "winmgmts:{impersonationLevel=impersonate}!//"&
ComputerName &""
Once you’ve made the connection, you only need to query the properties of the
BIOS class:
Then, you dig even further by getting the data out of the Serial Number
property. Not only that, what good is data if you can’t . . .
Not only can you obtain the serial number from the WMI repository’s BIOS
class, there is a horde of other properties. Remember, this is just one class in
WMI. There is so much information stored in WMI that it will boggle your mind.
Look at the following table for a sampling of what you can find in the BIOS
class alone:
Property Description
32
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
InstallDate When the object was installed—a lack of a value does not
indicate that the object is not installed.
33
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
The best resource of information about the WMI repository is included in the
Help files of the WMI Software Development Kit (SDK). I realize this sounds
like a programmer’s tool, but there’s a huge amount of information included in
the WMI SDK that is extremely useful to VB scripters. You’ll be able to locate
the WMI SDK download at the following Microsoft MSDN web page:
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/wmisdk/wmi/ wmi_start_page.asp.
NOTE: For certain functions (like obtaining serial numbers), certain computer
requirements must be met. A specific version of WMI is required on each
computer from which you want to retrieve the serial number. WMI 1.5 or better
is the requirement. Your computer’s BIOS must support a special industry
standard called SMBIOS, and the version number must be compatible with 2.1
or better. For more information on SMBIOS, see the Desktop Management Task
Force (DMTF) website: http://www.dmtf.org. If you are curious if your
computers are SMBIOS compliant, check with the computer's manufacturer.
34
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
Set objWbemSvc =
GetObject("Winmgmts://./root/MicrosoftSqlServer")
You can actually get a list of the providers available on a given system with—
what else—a VB script. Run the following on any computer to retrieve the list
of available providers:
35
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Your abilities for connecting to resources that you administer are endless. I
hope you’re realizing that VB script is a mighty powerful tool.
36
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
Dim colProcesses
Dim refProcess
Dim refWMI
Dim strMoniker
Dim strQuery
Dim numLow
Dim numHigh
Dim i
The formatting doesn’t even have to end there. You can use special characters
to document your script. I discuss that in the next Question.
As a simple suggestion, you should comment the heck out of your code. Using
the remark statements, input as much information about your script as
37
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
possible. You’ll thank yourself later. Sure, it takes a bit more time and feels like
a pain, especially when you’re working feverishly on a new code solution, but
the benefits definitely outweigh the time you lose initially.
You can find more information about these courses on Microsoft’s training
and certification website: http://www.microsoft.com/traincert/default.asp.
38
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
entire document with a VBScript and the SendKeys function—not that you
want to do that, but that ability exists.
Some keystrokes do not generate characters (such as ENTER and TAB). Some
keystrokes represent actions (such as BACKSPACE and BREAK). To send
these kinds of keystrokes, send the arguments shown in the following list:
à BACKSPACE {BACKSPACE},
{BS}, or {BKSP} TAB {TAB}
39
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
NOTE: A couple other available technologies send keystrokes with which you
might already be familiar. You can use these scripting tools either alone or
with VBScript.
41
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
ntellimirror.asp). You can even utilize web pages and login scripts as a
mechanism.
Think of it in terms kitchen appliances. You have a toaster on one hand and a
toaster oven on the other. Both can toast bread, but the toaster oven can do
so much more. You can settle for a VBScript-only solution for delivering
software, or you can utilize a full systems management application to deliver
software, support users remotely, inventory the hardware and software of the
company’s equipment, control software licensing, etc. Particularly, from the
software delivery aspect, a systems management application can offer some
comprehensive features that “manual” solutions can’t offer. For example, how
would you like to be able to target all Windows XP computers, with enough
hard disk space, and that meet the application’s RAM and video requirements?
Or, be able to distribute software based on a schedule like: only deliver the
software to a specific group of computers, next Tuesday at 3:00am?
VBScript works with each of these systems management mechanisms. You just
need to know how to code a script to kick-off the installation of an application.
The following script uses the WSHShell.Run command, to run Explorer.exe
and to open with the C:\WINNT directory as the initially displayed folder. You
can modify the path statement following the Explorer.exe command to tweak
the command to open in any folder you like.
Dim oWSHShell
Set oWSHShell = WScript.CreateObject("WScript.Shell")
oWSHShell.Run "Explorer.exe C:\WINNT"
42
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
43
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
WorkOffline:
Table 6 – Printer Properties Available in the WMI Repository
Installing Printers
Printer installations are a pesky prospect, and they always have been. Because
of the way a printer installation interacts with the computer at the hardware
level, it’s usually best to just use the vendor’s printer installation files. That’s
not to say that VBScript can’t be utilized to kick-off printer software
installation, or another interesting feature of which you may not be aware.
44
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
Windows 2000 and later have a DLL that can be used to install printers with
configuration options. PrintUI.dll contains the functions that post Windows
2000 computers use when installing printers, and you can access the functions
with a single set of command line options.
You can view all of the options available to you through the PrintUI.dll file by
typing the following in the Start | Run dialog box:
rundll32 printui.dll,PrintUIEntry /?
When this command runs, the following dialog box is displayed, allowing you to
review the options:
When the script runs, it prompts for the UNC to the server and printer share.
45
JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I
Dim p
p = InputBox("Enter the network path to the printer you want to
install:", "Add Printer", "\\Server\PrinterName")
WScript.CreateObject("WScript.Shell").Run cmd
End If
Summary
Someone once said that your journey begins with your first step. What a
profound statement. By picking up this book and perusing through it, your
journey has already started. You can’t turn back now. If you do, you will be
stuck at the base of the mountain forever. True enlightenment can be obtained
by treading onward, picking up pieces here-and-there, downloading code and
figuring out what it’s doing and how it’s doing it, reusing the code, and finally,
using the basics as a foundation. As more and more people wear down their
soles on the Geek highway, your plight in life will become nothing more than
their roadside scenery. As their speed picks up, you will meld into the blur of
the rushing landscape.
VB scripting is more than just a momentary fascination. It is a stepping-stone
in the evolution of a new career, a new talent, or of advancement to a higher
level. In the coming years, or even months, enterprise scripting will ultimately
become a requirement for employment. Reading and remembering the basics
outlined in this book gives you a solid foundation to construct a good working
knowledge of scripting.
46
GETTING STARTED W I T H VISUAL BASIC SCRIPTING
R E S O U R C E S
47