Top Banner
Just the FAQs to Understanding VBScripting Basics Part I: Getting Started with Visual Basic (VB) Scripting SUPER-GEEK, STEP I—OR, GETTING TO THE MOUNTAIN
50

Just the FAQs to VB Scripting Basics

Nov 29, 2014

Download

Documents

viswabharani
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Just the FAQs to VB Scripting Basics

J u s t t h e FAQs t o U n d e r s t a n d i n g

VBScripting Basics

Part I: Getting Started with Visual Basic (VB) Scripting

S U P E R - G E E K , S T E P I — O R , G E T T I N G T O T H E M O U N T A I N

Page 2: Just the FAQs to VB Scripting Basics

Rod Trent

Page 3: Just the FAQs to VB Scripting Basics
Page 4: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

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.

Q: What is Windows Script Host? Have you ever been to a party or gathering where one of your spouse’s friends wants to talk “shop?” Maybe “shop” to them is delivering mail for the US Postal Service, but you really have no idea how to interact with the conversation. Instead, you just nod your head and smile, and respond with phrases you’ve seen on television or in the movies. Either one, you have latched onto a universal topic that has no wrong answer, two, you’re doing a heck of a job hiding your blank expressions and should be nominated for an Emmy, or three, the host of your conversation is silently laughing at you. I’d speculate the latter to be the case. In social circles, though, that is the honorable thing to do. No matter how stupid you look or sound, it is just good etiquette to “play along.”

M

Page 5: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

2

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.

NOTE: The minimum requirement for WSH to function is Internet Explorer version 3.0 or later. WSH relies on the Visual Basic Script and Java Script engines provided in Internet Explorer.

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.

Q: What can I do with WSH? Imagine yourself on a deserted island, much like Tom Hanks in the movie “Cast-away.” If you could pick one person to be stranded with you, who would it be? What if one of your choices was MacGyver? If Tom Hanks could have been shipwrecked with the 80’s TV character, how long do you think they would have been stranded? I remember seeing a couple episodes of MacGyver where he made a nuclear reactor from a bunch of nothing: a box of fried clams and a spool of thread. If he can do that, surely, he could have fashioned a satellite phone from a hollow log and that crazy volleyball Tom Hanks named “Wilson.”

Page 6: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

3

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:

Print messages to the screen

Map network drives

Connect to printers

Retrieve and modify environment variables

Modify registry keys

Write and read files

Retrieve computer inventory information

Q: Which version of WSH do I need? Windows Script Host is an ingenious tool, comparable to other technologies. Take for example, your old DVD player. It plays the latest DVDs, but it’s too outdated to play MP3 CDs. Having that kind of functionality is a home theater pundit’s dream. So, after a short trip to the local electronics store and a quick cable changeover, the latest remix of the Elvis song, “Little Less Conversation,” is slicing the living room with its funk beat. However, does the new DVD player still play your old DVD movies? You bet. If the DVD manufacturer stopped supporting the playing of older DVD disks, just to add MP3 capability, there would be serious backlash – and quite a few product returns.

WSH may not be as cool as the big “E” (or it may be to some of you – God forbid), but it works much the same way as that new DVD player. Installing the latest and greatest version of WSH yields big benefits. Not only will your computers be able to utilize the latest functions of the updated engine, but the old functions will continue to work too. Plus, version 5.6 adds some extra neat, new features, as well as bolsters security. I cover this in the next section.

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.

Page 7: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

4

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.

Q: How do I deploy the latest version of WSH? This is the age-old question, isn’t it? When a new patch or security update is released, it suddenly becomes critical that it is deployed throughout your company. If your company consists of 12 employees who share 5 computers, then you’re probably feeling pretty comfortable and getting the sleep requirements recommended by the Surgeon General. However, if you happen to work for a company with 70,000 employees in 80 countries, each with their own computer, your post-work life is most likely non-existent. You feel more like a 1st year Med student than someone who spent their early years worshipping bits and bytes, thinking what a cool job working with computers could be. Your alarm clock is your pager and each person in your company has beeped you awake more than once.

There are numerous ways to deploy updates, particularly a new WSH version. Several come to mind, like Microsoft Systems Management Server (http://www.microsoft.com/smserver/default.asp), Altiris Deployment Solution (http://www.altiris.com/products/deploymentsol/), login scripts, batch files attached to emails, etc. Nevertheless, the scope of this book is not to delve too deeply into software deployment technologies. Instead, I only want to give you the information that allows you to use your favorite method of deploying the latest WSH version, successfully.

The installation executable name for WSH is Scripten.exe, downloadable from Microsoft’s scripting website at: http://msdn.microsoft.com/downloads/ default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/728/ msdncompositedoc.xml&frame=true.

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.

Page 8: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

5

The installation has a few options for controlling how it performs, as shown in Figure 1 below.

Figure 1 – Windows Script Host 5.6 Installation Options

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)

Page 9: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

6

represents the known switches for Microsoft patch installations. Your mileage may vary.

Switch Definition

/q Quiet mode—skips all user prompts

/q:u User quite mode—shows some dialog boxes

/q:a Admin quite mode—does not show any dialog boxes

/r:n Never restart—do not restart the computer even if it is necessary to complete the installation

/r:i Restart if necessary—automatically restart the computer if it is necessary to complete the installation

/r:a Always restart—always restart the computer after 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

/n:v No version checking—installs the program over any previous version

Table 1: Alternate Installation Switches

Q: Which features does WSH 5.6 offer me? Now you are thoroughly interested in WSH version 5.6. Your interest has been piqued and you know that storing extra information in that brain of yours will make you a star at the next Geek Games.

WSH 5.6 is quite a leap from earlier versions. Of course, Microsoft included bug fixes. A service level can’t be upgraded without addressing current problems. There are quite a few people in the IT industry who would whine for weeks if a specific bug wasn’t addressed. For a list of the bug fixes, read through the Windows Script Host 5.6 documentation at: http://msdn.microsoft.com/ downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/728/msdncompositedoc.xml&frame=true.

Page 10: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

7

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.

NOTE: In the same registry key, if IgnoreUserSettings is 0 or not present, then the HKCU settings will take priority over the HKLM settings. If IgnoreUserSettings is 1, then the security settings will always be taken from HKLM, though the individual preference settings will still apply the user’s settings.

Registry Value Description

Enabled If 1, then WSH is enabled. If 0, WSH is disabled. Default is 1 if not present.

Remote If 1, then this machine may run scripts remotely. If 0, it may not. Default is 0 if not present.

TrustPolicy If 0, then all scripts are run. If 1, then unsigned or untrusted

Page 11: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

8

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.

UseWINSAFER On Win2K, WinNT, Win98, WinME: no effect. On WinXP: controls whether to consider the Software Restriction Policies (SRP, formerly known as WinSafer) when running scripts. The SRP settings are more thorough and robust than the simple signature checking that the TrustPolicy setting was designed for. Default is 0 if not present.

LogSecurityFailures On Win2K, WinNT, Win98, WinME: no effect. On WinXP: controls whether to consider the Software Restriction Policies (SRP, formerly known as WinSafer) when running scripts. The SRP settings are more thorough and robust than the simple signature checking that the TrustPolicy setting was designed for. 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.

Page 12: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

9

Running Scripts Remotely You can load scripts onto several remote computer systems and start them all running simultaneously. While a remote script is running, you can check its progress. After it has finished, you can ensure that it ran correctly or determine the cause of its premature termination.

Processes as Objects You determine the status of spawned processes and access their standard I/O streams.

Set the Current Active Directory You can determine/modify the active process’s current working directory.

Q: What’s the difference between WScript.exe and CScript.exe? Friday night is the big shindig where you may receive an award for your excellent service this year. You worked through three colds and one bout of laryngitis and made it through the entire year without missing one in-service day of work. It’s a black-tie affair, and your wife is expected to attend with you as your Plus One. Frankly, due to your unflinching dedication, you’ve summarily forgotten this year to take your wife to a movie or even a simple dinner. So, this night out seems to her the best chance to live-it-up, be seen, and set the mode in style. She’s so excited that she’s been out every day to several different shopping centers, looking for just the right thing to wear. With so much on the line, which car do you take to the company ceremony? Do you take the beat-up Chrysler that you drive to and from work every day—the same one that has McDonald’s coffee stains in the passenger seat—or do you take the “good” car, the one you let your wife drive?

If you have to think about that too long, you may need to take a few days of “sick” time the following year.

Just like there’s a car for every occasion or an outfit that goes best with an event, WSH has two specific scripting engines that are used for appropriate instances. You can run WSH either from the protected-mode Windows-based host (Wscript.exe) or from the real-mode command-shell-based host (Cscript.exe).

The difference between the command-line and the Windows-based engines is only in the output — WScript.exe generates windowed output, while CScript.exe sends its output to the command window in which you started it. The only real way to understand this difference is to see a script in action.

Page 13: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

10

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.

Figure 2 – Window Prompt for a Computer Name to Query

Figure 3 – Cscript.exe Output for the Service Information Script

Below is the script (notice the WScript.Echo statements).

Page 14: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

11

Service Information for CScript.vbs

ComComputerName = InputBox(“Enter the name of the computer you wish to query”)

winmgmt1 = “winmgmts:{impersonationLevel=impersonate}!//”& ComputerName &””

Set SPSet = GetObject( winmgmt1 ).InstancesOf (“Win32_Service”)

WScript.Echo “==========================================”

WScript.Echo “Service Information for “ & “”& ComputerName &””

WScript.Echo “==========================================”

For each SP in SPSet

WScript.Echo “Service Name: “ & SP.Name

WScript.Echo “Location: “ & SP.PathName

WScript.Echo “PID: “ & SP.ProcessID

WScript.Echo “Type of Service: “ & SP.ServiceType

WScript.Echo “Service State: “ & SP.State

WScript.Echo “==========================================”

WScript.Echo “==========================================”

next

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.

Figure 4 – Crazy WSH Window Meant for CScript.exe

Page 15: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

12

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.

Figure 5 – Wscript.exe Running as a Windows Process

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:

Page 16: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

13

Service Information for WScript.vbs:

For each SP in SPSet

MsgBox “Service Name: “ & SP.Name & vbcrlf &_

“Location: “ & SP.Pathname & vbcrlf &_

“PID: “ & SP.ProcessID & vbcrlf &_

“Type of Service: “ & SP.ServiceType & vbcrlf &_

“Service State: “ & SP.State

Next

The output would be much kinder (as shown in Figure 6).

Figure 6: Service Information Output Designed for WScript.exe

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.

NOTE: When WSH is installed, WScript.exe is designated as the default scripting engine. Then, anytime a VB script or Java script is executed, WScript.exe jumps to attention and hosts the script for you. If you code the majority of your scripts CScript.exe to host, you may want to change the default. You can do this by running the following command-line:

cscript//h:cscript

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

Page 17: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

14

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.

Q: What command-line options do the scripting engines offer? In the early days of computing, a horde of commands hid spectacular options. These options came in the form of command-line options and arguments, much like the option in the previous section to change the default scripting engine. Somewhere along the line, someone got smart and started incorporating these options and arguments into a neat, new argument all its own. This argument came to be called the /? (slash-question mark), and sometimes the /help (slash-help). Very cool—what was once fodder for a secret society of programmers is now at your disposal to do with what you will.

WSH is no exception. Both WScript.exe and CScript.exe have command-line options and arguments available. You can access them the normal way, by typing in the engine with the /? (WScript.exe /? or CScript.exe /?). Instead of writing out the switches for each engine, it’s best to go right to the source. Figure 6 shows the command-line options for WScript.exe, and Figure 7 displays CScript.exe’s options.

Figure 7 – Wscript.exe Command-Line Options

Page 18: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

15

Figure 8 – Cscript.exe Command-Line Options

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.

Q: What are the differences between VBScript and JavaScript? When you’re just starting out, heading down that scripting path, you come across your first conundrum: two scripting languages. Which one you use really depends on what your needs are but also what your tastes are like. Some people choose Coke; some choose Pepsi. Unfortunately, the scripting languages don’t have someone like Britney Spears to lead you in one direction or the other. There is no song and dance routine to help you decide which language is best for you. If there was, I suspect more people would be interested in scripting.

JavaScript is a scripting language targeted toward web development. If you’re working directly with web technologies, JavaScript should be your tool of choice. Sun Microsystems (http://www.sun.com/) derived the name JavaScript from the original Java language they developed.

VBScript is used, primarily, in companies that want to manage their computing and networking environment. From inventorying computer hardware, to changing network passwords, to deploying software, VBScript is a powerhouse for the enterprise. The name VBScript is taken from Microsoft’s (http://www.microsoft.com) own Visual Basic programming language.

Page 19: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

16

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.

Q: How can I protect my scripts? As outlined in the previous FAQ, you can compile code written with development languages, but you can’t compile script language code. Compiling code for a programming language also keeps unwanted eyes from viewing and modifying the code that a programmer worked hard to create. You can do something similar with scripts too. We call this “encoding.” A “script encoder” is a simple command-line tool that enables script developers to encode the final script so that it cannot be viewed nor the source modified. Microsoft has a script encoder available for download at the following location: http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.asp?url=/MSDN-FILES/027/001/789/msdncompositedoc.xml.

After JavaScript has been encoded, the file extension (.js) is changed to .jse. VBScript file extensions are changed from .vbs to .vbe. This new file extension designation allows you to see quickly whether a script has been encoded or not.

I did say the VBScript is a powerhouse, didn’t I? Well, if it’s so powerful, why can’t it encode itself? It can. I hate to throw a lot of code at you in a book on VBScript basics without spending time explaining it, but you can always come back and play with the code later on, once you’ve become more comfortable with the scripting languages. The following will encode any script written with VBScript or JavaScript. All you have to do is have this script sitting somewhere in the file system, and then drag and drop the script you’ve created onto it. Your script is encoded automatically!

Page 20: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

17

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

Page 21: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

18

Set DestFile = fso.OpenTextFile(DestPath, 2, true)

DestFile.Write Left(EncodedText, Len(EncodedText) - 1)

DestFile.Close

Set DestFile = Nothing

End If

Set fso = Nothing

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.

Q: What’s the best way to learn to script? This question comes up quite a bit on web forums and email discussion lists. When an individual finally decides that “today is the day” to start on the path to scripting, he turns to those he feels would know best where to begin. If you notice, every one to whom he asks this question will give a slightly different answer. Some will give a long list of scripting books; others will copy and paste links to their favorite scripting websites. Despite the laundry list, one point rings through every time: you learn by doing.

Stop and remember . . . way back . . . ok, even further than that . . . when you started learning how to drive a car. You probably gave your parents quite a few heart attacks, but they knew the only way you were going to get the driving thing down was to sit behind the wheel and work out your own rhythm. Your dad gave you the basics: “You sit behind the steering wheel. The brake pedal is on your left, and the gas pedal is on your right. That’s the turn signal. No, no, on the other side—those are the wiper blades.”

Better than learning to drive, you won’t have to worry about needing a licensed scripter sitting in the passenger seat. You’re on your own, doing your own thing, learning at your own pace, and getting your own rhythm. What’s more, unless you write a script that reboots the file servers and test it in a production environment, you won’t cause too many heart attacks.

There is no licensing fee for a script. As you are surfing the web, finding scripting websites and reviewing script code, grab it all and save it somewhere on your hard drive. Be as script-hungry as you like, and no one will care.

There are quite a large number of resources available to help you learn scripting. Grabbing scripts from these resources and rolling up your sleeves and just digging in is the main key to understanding the languages. One of the most exciting aspects of the scripting community is each individual’s

Page 22: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

19

willingness to share what they’ve done. A couple quick changes here, an addition of a line or two, and a script you found or received from someone is ready to work in your environment. Remember, though, someday other people will be just like you – chomping at the bit to learn how to script. Don’t be stingy and keep your scripts locked up in a box somewhere. By sharing the solutions you have scripted, you not only help the “newbies” get up to speed, but you help keep a community growing and going strong.

Whether you believe it or not, your best and most loyal companion on your scripting journey is the actual scripting documentation provided by Microsoft. “What?” you say, “You mean the same company that spearheaded the effort to rid the world of product manuals?” Yep, the exact same. I use the documentation regularly. It not only contains comprehensive information, but also includes script examples in both VBScript and JavaScript that you can copy and work with yourself. A quick jaunt over to Microsoft’s scripting website (http://msdn.microsoft.com/scripting) gives you the download links for all of the documentation. Here’s a list of what’s available:

Script Debugger Documentation—http://msdn.microsoft.com/ library/en-us/sdbug/Html/sdbug_1.asp

Remote Scripting Documentation—http://msdn.microsoft.com/ library/en-us/rmscpt/Html/rmscpt.asp

JScript Documentation—http://msdn.microsoft.com/library/

en-us/script56/html/js56jsoriJScript.asp

VBScript Documentation—http://msdn.microsoft.com/library/ en-us/script56/html/vtoriVBScript.asp

Windows Script Host Documentation—http://msdn.microsoft.com/ library/en-us/script56/html/wsoriWindowsScriptHost.asp

Windows Script Components Documentation—http://msdn.microsoft.com/library/en-us/script56/html/lettitle.asp

Microsoft Windows Script 5.6 Documentation—http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/728/ msdncompositedoc.xml&frame=true

Microsoft Windows Script 5.6 Download—http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.asp?url=/msdn-files/027/001/733/msdncompositedoc.xml

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

Page 23: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

20

MyITforum.com is the premier website for systems administrators. Pure and simple, if you have a problem, you can find an answer here. MyITforum.com has an entire article section dedicated to VB scripting with new articles posted daily. There’s also a dedicated VB scripting web forum where people post problems and others post answers, complete with script examples. Before you click away from the site, make sure to check out the VB scripting downloads area. Not only can you seize some free script downloads, but as a site member you can post your own solutions. The majority of the online scripting community runs through this site.

Microsoft’s TechNet Script Center—http://www.microsoft.com/ technet/treeview/default.asp?url=/technet/scriptcenter/default.asp

Recently inaugurated, this site is quickly becoming the epicenter for script downloads. This repository of scripts continues to grow. There has been no formal communication as to a schedule when new scripts are released, so you’ll need to check back periodically.

WSHScripting.com—http://www.wshscripting.com/

Another hit-and-run site for grabbing scripts, WSHScripting.com offers a nice library of downloadable script solutions.

Win32Scripting—http://cwashington.netreach.net/main/

I know, I know, the URL for this website is deceiving. Just typing the link into your browser address line gives you the feeling that you are being whisked away to someone’s personal homepage, fraught with strange web cursors and a zillion pop-up advertisements. However, that’s not the case. The Win32Scripting website is a well-organized library of script submissions. The search engine is very useable, allowing you to pinpoint downloadable scripts according their topic matter. This site is probably one of the first ones I found when I started out on my quest for the scripting grail. The only downfall of the website is that the navigation is a bit much and takes a while to master. It’s like reengineering a car door handle to make it more complicated, just because you can. You’ll see what I mean when you visit the site.

Q: Aren’t Windows scripts unsafe? There has been much hubbub in the pipes over the last couple years about Windows scripts being a security risk. There has been so much activity along these lines that Microsoft has released several security patches for programs like Microsoft Outlook that stop scripts from running automatically on a computer. Anti-virus program vendors like Symantec and McAfee have kept the fires burning late into the night, concocting updates to help minimize the potential damage that can be caused from unsafe scripts.

At one point in time, Windows scripts were your worst enemy, but so much effort has gone into fixing the problem that Windows scripts are now as safe as

Page 24: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

21

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

2. Key = JSFile\Shell

o New Value = Edit

3. Key = VBSFile\Shell

o New Value = Edit

4. Key = VBEFile\Shell

o New Value = Edit

5. Key = WSFFile\Shell

o New Value = Edit

6. Key = WSHFile\Shell

o New Value = Edit

7. Key = WSHFile\Shell\Edit\command

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.

Page 25: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

22

Q: What tools do I need to start scripting? Chomping at the bit, are you—trying to get your tools in place and your desktop squared away? Well, before you head out to the local software store or start pounding Google.com with search requests, you may be surprised to know that you already have everything you need to get scripting. The majority of the scripting community uses the simple tool included with all Windows computers—drum roll please—Notepad. You can open any VB script (except for encoded scripts) in the simple text editor. Sure, there are other tools that can maximize your scripting time by colorizing VBScript methods and routines for readability and automating specific functions, but you can’t beat the price of Notepad.

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.

Figure 9: Encode.vbs Opened in Notepad

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

Page 26: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

23

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).

Figure 10: Script Error at Line 2 Character 1

The error message indicates a problem on Line 2 and in Character 1. Showing an error in Character 1 generally means something in the entire line is messed up. At least you have a clear direction to start debugging though. If you have an enormous script, getting to line number 567 can be a problem. Instead of counting lines, do this:

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.

Figure 11: Go to Line Command in Notepad

2. Just type in the offending line number, and Notepad whisks you to the appropriate line straightaway.

Page 27: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

24

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.

Figure 12: The ConTEXT Programmer’s Editor

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!

Page 28: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

25

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:

80196 Assembler

AnSys Macros

AutoIt

AutoLisp

AWK

Clipper

Cobol

ConTEXT Highlighter Files

CSharp

CSS

DCL Language

DOS Batch

Euphoria

HP48

JCL (Job Control Language)

KiXtart

Latex

Liberty BASIC

MIPS Assembler

PCBus

PowerPC GNU Assembler

SciLab

SkdTXT

SNMP MIB

SWI Prolog

VHDL

Visual IRC v2.0

Windows resource scripts

x51 Assembler

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

Page 29: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

26

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.

Q: How can I make others run my scripts? VBScript would be a monotonous technology if you had to keep your scripts to yourself and run them only on your computer. Granted, that could prove to be a lot of fun, but people will, eventually, start looking at you strangely (maybe more strangely than they do now). You can only play scripting Solitaire for so long. Besides, what good is a management tool without the ability to use it across all computers in the company?

Page 30: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

27

VBScripts can run on remote computers in a few different ways.

In a login script

From a network share

Copied to the remote computer and executed there

From a web page

With a remote execution utility

By utilizing Remote WSH

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.

Example of VBScript Inserted into Login Script The following bit of VB script code provides an example of something you might want to place into your login scripts. This “codelet” simply maps the network drives O and Q for the computer logging into the network. With just a few lines of code, you can provide these network drive mappings.

Dim net Set net = CreateObject("WScript.Network") net.MapNetworkDrive "O:", "\\server\share"

net.MapNetworkDrive "Q:", "\\server\share"

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

Page 31: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

28

personally utilize to get software to the end-user. VB scripts work just fine using a hard-coded drive letter or a UNC path.

Run on Remote Computer Since VB scripts can run flawlessly on a local computer, it makes sense to understand that if you can get the script to the remote computer, it will run. Using any method you currently employ, just have the script copied to the remote computer into a directory you specify and formulate your plans to have the computer execute the script.

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.

Remote Execution Util ity Several utilities on the market allow you to execute programs on remote computers. You just sit in the comfort of your cubicle, type out a few instructions on your keyboard, and the remote computer executes your commands. If you’ve watched many horror movies with a mad dictator or scientist, this is where you would hear an evil laugh emanate—Bwahahahaha . . .

One of the more popular tools in this area is from SysInternals. SysInternals offers a slew of freeware utilities geared toward aiding the systems administrator.

PsExec is the utility that allows remote execution of commands/programs. It doesn’t need to be installed on the remote computer, just run from yours, so there’s no overhead on the remote computer. PsExec utilizes the following command line options:

usage: psexec \\computer [-u username [-p password]] [-s] [-i] [-c

[-f]] [-d] program [arguments]

-u Specifies optional user name for login to remote computer

-p Specifies optional password for user name—if you omit this you will be prompted

Page 32: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

29

to enter a hidden password.

-s Run remote process in the System account.

-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.

program Name of the program to execute

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.

Page 33: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

30

Setting-Up Remote WSH

1. Install WSH V5.6 on the machine. If you are using Windows XP or have installed Internet Explorer 6 or greater, WSH 5.6 has already been installed.

NOTE: WSH 5.6 is available for download from the web at http://msdn.microsoft.com/scripting.

2. Add yourself to the remote machine’s Local Administrators group.

3. To enable Remote WSH, use the System Policy Editor (Poledit.exe) on the computer to incorporate the windowsscript.adm policy file.

NOTE: An administrator who wants to enable Remote WSH must either acquire the Windows 2000 resource kit or use http://msdn.microsoft.com/scripting to acquire the necessary windowsscript.adm file that contains the WSH settings. The windowsscript.adm file must be copied to the computer that sets the applicable group’s policies. Although it is not necessary to copy the file to the server’s \WINNT\INF directory, this is nonetheless where the default adm files are located.

Hey, I need a little help here. I need to override Word’s blah, blah, blah

ADDITIONAL NOTE: For more information on Poledit.exe, see the Poledit.exe’s online help system. Poledit.exe can be run from the Start| Run command.

4. WSH should now be enabled on the machine.

Q: Can I retrieve remote information from my computer? If you have kids, then you know Bob the Builder. If not, you need to get “with it” (http://www.hitentertainment.com/bobthebuilder/). There’s a little jingle that goes with the kids’ program. My youngest has been singing it since he was much younger than he is now. For a VB scripter, it would go something like

Page 34: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

31

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.

Figure 14: Dialog Box Requesting Remote Computer to Connect to

‘Dialog Box Setup:

ComputerName = InputBox("Enter the name of the computer you wish to query")

‘Connection string (handshake)

Page 35: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

32

winmgmt1 = "winmgmts:{impersonationLevel=impersonate}!//"& ComputerName &""

Once you’ve made the connection, you only need to query the properties of the BIOS class:

‘Connecting to the BIOS class

Set SNSet = GetObject( winmgmt1 ).InstancesOf ("Win32_BIOS")

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 . . .

‘Giving the script a constant (SN) to work with

for each SN in SNSet

‘Displaying the computer’s serial number in a dialog box

MsgBox "The serial number for the specified computer is: " & SN.SerialNumber

Next

Figure 15: Dialog Box Displaying Computer Serial Number

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

BiosCharacteristics BIOS characteristics supported by the system as defined by the System Management BIOS Reference Specification

Page 36: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

33

CurrentLanguage Name of the current BIOS language

Description Description of the object

IdentificationCode Manufacturer's identifier for this software element—often this will be a stock keeping unit (SKU) or a part number.

InstallDate When the object was installed—a lack of a value does not indicate that the object is not installed.

ListOfLanguages List of names of available BIOS-installable languages

Manufacturer Manufacturer of this software element

Name Name used to identify this software element

PrimaryBIOS Indicates whether this is the primary BIOS of the computer system

ReleaseDate Release date of the Win32 BIOS in the Coordinated Universal Time (UTC) format of YYYYMMDDHHMMSS.MMMMMM(+-)OOO.

SerialNumber Assigned serial number of the software element

SMBIOSBIOSVersion BIOS version as reported by SMBIOS

SMBIOSMajorVersion Major SMBIOS version number—this property is null if SMBIOS is not found.

SMBIOSMinorVersion Minor SMBIOS version number—this property is null if SMBIOS is not found.

SMBIOSPresent Indicates whether the SMBIOS is available on this computer system

Status Current status of the object—various operational and non-operational statuses can be defined. Operational statuses include OK, Degraded, and Pred Fail. (An element, such as a SMART-enabled hard drive, may be functioning properly but

Page 37: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

34

predicting a failure in the near future). Non-operational statuses include Error, Starting, Stopping, and Service. The latter could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither OK nor in one of the other states.

Values are OK, Error, Degraded, Unknown, Pred Fail, Starting, Stopping, and Service.

TargetOperatingSystem Target operating system of the owning software element

Version Version of the BIOS—this string is created by the BIOS manufacturer.

Table 3 – Sampling of WMI Repository BIOS Class Properties

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.

Page 38: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

35

Q: Can I query information for other things—like SQL Server? “Yes, you can!” Sorry, that was another Bob the Builder reference. If you’ve taken the time to visit the website, the song is probably stuck in your head, too.

To make it easier to access specific Microsoft server offerings, and to give better abilities to developers, Microsoft developed common “connectoids” called providers for many of their servers. Then, each provider includes a namespace or a number of namespaces. An example is the ADSI Service Provider, which includes several namespaces (shown in the table in this section.)

As an example, the following utilizes the same type of handshake to connect to an Internet Information Services (IIS) server (notice the item in bold):

Set IIsComputer = GetObject("IIS://" & TargetComputer)

The following will connect you to a Microsoft SQL Server:

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:

Set objProvider = GetObject("ADs:")

For Each Provider In objProvider

WScript.Echo Provider.Name

Next

Some common providers and namespaces:

Provider NameSpace Description

ADSI LDAP This namespace implementation is compatible with Lightweight Directory Access Protocol (LDAP).

Page 39: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

36

ADSI WinNT This namespace implementation is compatible with Windows NT®/Windows® 2000.

ADSI NDS This namespace implementation is compatible with Novell NetWare Directory Service (NDS).

ADSI NWCOMPAT This namespace implementation is compatible with Novell NetWare 3.x.

WMI Winmgmts This namespace implementation is compatible with Windows Management Instrumentation.

Table 4 – Common Providers and NameSpaces

Your abilities for connecting to resources that you administer are endless. I hope you’re realizing that VB script is a mighty powerful tool.

Q: In VB scripts I’ve seen, they are formatted a specific way. Is this important? No . . . and Yes. Is that a clear answer?

Programmers can be the messiest bunch of people on the planet, and that’s not just talking about their workspaces littered with Mountain Dew bottles, a dozen broken stress relief balls, and oodles of doodles of Bill Gates and Steve Ballmer sitting on mounds of cash. A programmer’s code can be a mess of strings, commented out to save to work on later. Organization is the last thing on their minds.

Will VB scripts work without this special formatting? You bet. As long as you follow the guidelines for creating your script, the script will function. It may be the messiest looking bit of chicken scratch, but it will work.

The special formatting is strictly for your benefit, the scripter. Well, it’s also a big benefit for anyone else wanting to understand and possibly modify your script later on.

Think about it . . . say you stuff all of your laundry into one drawer, and you want to find a single pair of socks. You have to dig through the entire drawer, past your shirts, under you underwear, and in between your pant legs, just to locate a pair of socks to wear. How much easier it would be if you put all socks in a drawer by themselves.

Script formatting is similar to this scenario. If you define all of your variables in one area of the script, you can always jump back quickly to troubleshoot or to add new variables. Most scripters initialize their variables at the very beginning of their scripts. Look at the following. It shows a series of variables, initialized at the beginning of the script. You can use variables initialized here throughout the entire script.

Page 40: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

37

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.

Q: Can I add comments to my scripts? If you’ve ever scripted anything before, you know how useful it is to make comments in your scripts. This goes a long way toward organizing the script text, as well as helping you remember what a specific section of the script is doing in the overall scheme of things.

In the old DOS batch file days, you could use the REM (remark) statement to add comments. When the batch compiler saw the REM, it skipped it. VB script has this type of function available, and that includes the old REM standby, as well as the apostrophe (‘) character.

However, there’s a bit more to it than that. If you use the REM statement on a line that contains other code, you must separate the REM statement and the code with a colon (:). Used on a line by itself, the colon is not required. An apostrophe (‘) can be used anywhere. Does it sound confusing? Try this:

MyStr1 = "Hello" : REM Comment after a statement separated by a colon.

MyStr2 = "Goodbye" ‘ This is also a comment; no colon is needed.

REM Comment on a line with no code; no colon is needed.

‘ Comment on a line with no code; no colon is needed.

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

Page 41: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

38

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.

Q: Does Microsoft have any official curriculum for VB script? While I’ve not attended these courses myself, I have heard excellent comments on them. Microsoft currently offers two courses for those interested in getting hands-on training for VB scripting.

Course Number Course Description

2433AC Visual Basic Script and Windows® Script Host Essentials

2439AC Scripting Microsoft® Windows® Management Instrumentation

Table 5 – Microsoft’s Office Curriculum for VB Scripting

You can find more information about these courses on Microsoft’s training and certification website: http://www.microsoft.com/traincert/default.asp.

Q: Can I use VBScript to send keystrokes to Windows? The SendKeys function of VBScript would have made for an interesting X-Files episode. I can see it now…Moulder and Scully are called to a local company to investigate strange writings on computers – all done without any user input. Scully tries to convince Moulder that there has to be a scientific reason behind it. Maybe it’s just the systems administrator using VBScript to harass the end-user population. Moulder decides it’s the work of technology obtained through the Roswell crash of 1947. He goes on to prove that the systems administrator is actually the only survivor of the Roswell saucer crash.

The SendKeys function of VBScript probably one of the most popular functions. You can actually send keystrokes to the Windows shell, allowing you to automatically click through dialog boxes, or input text. You can also send any letter or number available on the computer’s keyboard. You could write an

Page 42: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

39

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} BREAK {BREAK} CAPS LOCK {CAPSLOCK} DEL or DELETE {DELETE} or {DEL} DOWN ARROW {DOWN} END {END} ENTER {ENTER} or ~ ESC {ESC} HELP {HELP} HOME {HOME} INS or INSERT {INSERT} or {INS} LEFT ARROW {LEFT} NUM LOCK {NUMLOCK} PAGE DOWN {PGDN} PAGE UP {PGUP} PRINT SCREEN {PRTSC} RIGHT ARROW {RIGHT} SCROLL LOCK {SCROLLLOCK}

TAB {TAB} UP ARROW {UP} F1 {F1} F2 {F2} F3 {F3} F4 {F4} F5 {F5} F6 {F6} F7 {F7} F8 {F8} F9 {F9} F10 {F10} F11 {F11} F12 {F12} F13 {F13} F14 {F14} F15 {F15} F16 {F16}

To send keyboard characters that are comprised of a regular keystroke in combination with a SHIFT, CTRL, or ALT, create a compound string argument that represents the keystroke combination. You do this by preceding the regular keystroke with one or more of the following special characters:

Page 43: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

SHIFT +

CTRL ^

ALT %

Example 1: MS Calculator Automation The following SendKeys example, runs MS Calculator and sends keystrokes to make a calculation.

set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "calc" WScript.Sleep 100 WshShell.AppActivate "Calculator" WScript.Sleep 100 WshShell.SendKeys "1{+}" WScript.Sleep 500 WshShell.SendKeys "2" WScript.Sleep 500 WshShell.SendKeys "~" WScript.Sleep 500 WshShell.SendKeys "*3" WScript.Sleep 500 WshShell.SendKeys "~" WScript.Sleep 2500

Figure 16 – Output of the Calculator script

Example 2: Turning CAPs Lock On and Off The following example turns the Caps Lock key on and off:

Page 44: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

41

set WshShell = CreateObject("WScript.Shell") WshShell.SendKeys "{CAPSLOCK}"

Example 3: Turning Num Lock On and Off This example turns the Num Lock key on and off:

set WshShell = CreateObject("WScript.Shell") WshShell.SendKeys "{NUMLOCK}"

“Pretty neat,” you might say, and you’d be right.

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.

1. AutoIT is one of these technologies, and if you’re not too keen on delving too deeply into VBScript, this may be an option for you. AutoIT is a simple scripting language that can be found at http://www.hiddensoft.com/AutoIT.

2. One of the precursors to VBScript was the ScriptIT language (also from Microsoft). ScriptIT is a tool for automating interactive software installations and system configuration tasks. This tool can be used to start a process, monitor the window titles of active processes, and when appropriate, send a set of keystrokes to the correct window. You can find more information on ScriptIT on this Microsoft website: http://www.microsoft.com/ntserver/techresources/deployment/NTserver/scriptit3.asp

Q: Can I deliver software with VBScript? Software delivery requires a mechanism. That’s not to say that VBScript can’t initiate the installation of software, just that it provides no “mechanism” for getting the software to the computers in your company. There are many software delivery mechanisms available, such as Microsoft Systems Management Server (http://www.microsoft.com/smserver/default.asp), offerings from Altiris (www.altiris.com), and Windows 2000 and 2003 Server Intellimirror (http://www.microsoft.com/windows2000/techinfo/howitworks/management/i

Page 45: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

42

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"

Q: Can I use VBScript to work with Printers? Just as VBScript can interoperate with many Windows components, you can also use it to manage printers in the Windows environment. You can interact with printers by adding or removing printer connections or by getting a specific printer’s properties.

Removing a Printer Connection The following script initializes the Windows Script Host's network component and then removes the printer connection that is assigned to the specified port. In this example, LPT1 is the specified port. You can modify this to LPT2, LPT3, COM1, COM2, etc. (essentially any supported printer port).

Set WshNetwork = WScript.CreateObject("WScript.Network") WshNetwork.RemovePrinterConnection "LPT1:"

Page 46: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

43

Adding a Printer Connection By utilizing the WSH network component, you can add a network-defined printer to any available port on the computer. In the example below, change the port (LPT1) to the port you require, as well as the server and print queue information (\\Server\Print1).

Set WshNetwork = CreateObject("WScript.Network") WshNetwork.AddPrinterConnection "LPT1", \\Server\Print1

Getting Printer Properties We talked about WMI earlier and the amount of data this repository provides. Well, data for printers are no exception. There is a horde of printer data you can retrieve just be accessing the Win32_Printer section of the WMI repository. It just depends on what you want information about, and how much data you want to retrieve.

Look at the following information, which represents a VBScript querying all of the printer properties available in WMI.

Attributes: Availability: AvailableJobSheets:

AveragePagesPerMinute:

Caption: CharSetsSupported:

Comment: ConfigManagerErrorCode: ConfigManagerUserConfig:

CreationClassName: CurrentCapabilities: CurrentCharSet:

CurrentLanguage: CurrentMimeType: CurrentNaturalLanguage:

CurrentPaperType: Default: False DefaultCapabilities:

DefaultCopies: DefaultLanguage: DefaultMimeType:

DefaultNumberUp: DefaultPaperType: DefaultPriority:

Description: DetectedErrorState: DeviceID:

Page 47: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

44

Direct: DoCompleteFirst: DriverName:

EnableBIDI: EnableDevQueryPrint: ErrorCleared:

ErrorDescription: ErrorInformation: ExtendedDetectedErrorState:

ExtendedPrinterStatus: Hidden: HorizontalResolution:

InstallDate: JobCountSinceLastReset: KeepPrintedJobs:

LanguagesSupported: LastErrorCode: Local: True

Location: MarkingTechnology: MaxCopies:

MaxNumberUp: MaxSizeSupported: MimeTypesSupported:

Name: NaturalLanguagesSupported: Network:

PaperTypesAvailable: Parameters: PNPDeviceID:

PortName: PowerManagementCapabilities:

PowerManagementSupported:

PrinterState: PrinterStatus: PrintJobDataType:

PrintProcessor: Priority: Published:

Queued: RawOnly: SeparatorFile:

ServerName: Shared: False ShareName:

SpoolEnabled: StartTime: Status:

StatusInfo: SystemCreationClassName: SystemName:

TimeOfLastReset: UntilTime: VerticalResolution:

WorkOffline:

Table 6 – Printer Properties Available in the WMI Repository

Install ing 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.

Page 48: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

45

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:

Figure 17 – PrintUI.dll Options

Utilizing the new functionality of PrintUI.DLL, the following VB script creates a printer connection, installs the printer to the printers folder, and makes it the default printer. When the script runs, it prompts for the UNC to the server and printer share.

Page 49: Just the FAQs to VB Scripting Basics

J U S T T H E F A Q S T O U N D E R S T A N D I N G V B S C R I P T I N G B A S I C S : P A R T I

46

Figure 18 – Prompting for Network Path and Printer

Then, it runs the proper PrintUI.dll switches to install the printer.

Dim p p = InputBox("Enter the network path to the printer you want to install:", "Add Printer", "\\Server\PrinterName") If p <> "" Then Dim cmd cmd = "rundll32 printui,PrintUIEntry /in /n" & p 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.

Page 50: Just the FAQs to VB Scripting Basics

G E T T I N G S T A R T E D W I T H V I S U A L B A S I C S C R I P T I N G

47

R E S O U R C E S

WMI Essentials for Automating Windows Management

Author: Marcin Policht;.Publisher: SAMS; ISBN: 0-672-32144-0

Marcin also writes articles on WMI for myITforum.com. His columnist homepage can be located at:

http://www.myitforum.com/contrib/default.asp?cid=894

Microsoft Windows 2000 Scripting Guide

Author: The Microsoft “Scripting Guys”;.Publisher: Microsoft Press; ISBN: 0-7356-1867-4

Windows Admin Scripting Little Black Book 2nd Edition

Author: Jesse M. Torres;.Publisher: Paraglyph Publishing; ISBN: 1932111875