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

Rod Trent

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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.

M

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

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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

2

As amazing as that show was (groan). but it works much the same way as that new DVD player. WSH is very much the MacGyver of the Windows computing environment.htm. A better question might be. without warning. 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. Installing the latest and greatest version of WSH yields big benefits. change the location of the content on their website. Microsoft can. does the new DVD player still play your old DVD movies? You bet. WSH may not be as cool as the big “E” (or it may be to some of you – God forbid).com/m/macgyver. 3 . but this specific link has been safe for a couple years. the latest remix of the Elvis song. NOTE: At the time of this writing. there would be serious backlash – and quite a few product returns.jumptheshark. “What can’t I do with WSH?” WSH is ideal for logon scripting. “Little Less Conversation. comparable to other technologies. I cover this in the next section. It plays the latest DVDs.com/scripting. Not only will your computers be able to utilize the latest functions of the updated engine. Take for example. However. Having that kind of functionality is a home theater pundit’s dream. but here’s a small sample. and machine automation. as well as bolsters security.GETTING STARTED W I T H VISUAL BASIC SCRIPTING EXTRA NOTE: For those too young or too cool to remember MacGyver. just to add MP3 capability. the latest version of WSH is version 5.6. You’ll understand further just how powerful WSH is as you read through the rest of the book. version 5.microsoft. So. look at this link: http://www.6 adds some extra neat. your old DVD player. after a short trip to the local electronics store and a quick cable changeover. but the old functions will continue to work too. but it’s too outdated to play MP3 CDs. which you can download from http://msdn. If the DVD manufacturer stopped supporting the playing of older DVD disks. Plus. administrative scripting. new features.” is slicing the living room with its funk beat.

you can still utilize the features you are already used to. Windows XP already has the most current version of WSH installed as part of the operating system load. downloadable from Microsoft’s scripting website at: http://msdn. Why? Well. and ME. the scope of this book is not to delve too deeply into software deployment technologies. In addition. For example.asp?url=/msdn-files/027/001/728/ msdncompositedoc. Make sure you use the correct download for the target platform. if you happen to work for a company with 70.microsoft.asp). login scripts. You are just adding new and exciting features to your ever-growing Geek Toolkit.com/products/deploymentsol/). batch files attached to emails.xml&frame=true. isn’t it? When a new patch or security update is released.com/smserver/default.asp?url=/downloads/sample. Your alarm clock is your pager and each person in your company has beeped you awake more than once. because the current version is backward compatible – meaning you are not going to lose functionality at all. There are numerous ways to deploy updates. successfully. Altiris Deployment Solution (http://www. The installation executable name for WSH is Scripten. to better answer which version of WSH you need. like Microsoft Systems Management Server (http://www. Several come to mind. your post-work life is most likely non-existent. Instead.com/downloads/ default. Nevertheless. they also offer new features of which you can take advantage. 4 .JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Okay. Q: How do I deploy the latest version of WSH? This is the age-old question. However. it suddenly becomes critical that it is deployed throughout your company.exe. particularly a new WSH version.microsoft. there is one download for Windows 2000 and others just for Windows NT. I only want to give you the information that allows you to use your favorite method of deploying the latest WSH version. You feel more like a 1st year Med student than someone who spent their early years worshipping bits and bytes.altiris. etc. not only do subsequent versions address bug fixes.000 employees in 80 countries. each with their own computer. thinking what a cool job working with computers could be. then you’re probably feeling pretty comfortable and getting the sleep requirements recommended by the Surgeon General. If your company consists of 12 employees who share 5 computers. TIP: There are specific downloads for the different versions of Windows. 98. let’s just say it’s best to have the latest and greatest version.

Installing the WSH upgrade. The WSH upgrade attempts to overwrite files during the installation process. will require the computer to reboot to finish the installation on the next boot. 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. they are flagged to be replaced during the computer boot process. Figure 1 – Windows Script Host 5. If some of these files are in-use during the install (and they will be). as shown in Figure 1 below. If it is your task to deploy the WSH upgrade to a multitude of computers during the workday. for the installation to finish completely. Until then. running the installation with the /Q switch will cause WSH 5.6 Installation Options EXTRA NOTE: Per Figure 1. 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.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. the new version of WSH will not work until the computer’s memory is flushed through a reboot.GETTING STARTED W I T H VISUAL BASIC SCRIPTING The installation has a few options for controlling how it performs. the following table (Table 1) 5 . Running the following command-line will cause WSH to install silently and to suppress any reboot message: scr56en. and you can notify the end-users to do this at their leisure. there are still some exceptions to the rule. In fact. In effect. even with the /Q switch. Then.6 to install quietly. there is a command option to accomplish this. the end-user will probably get upset if they have to close all of their applications and reboot the computer. the computer will need to be restarted. Remember when I said vendors now include all hidden switch functions in the /? command? Well.

Switch /q /q:u /q:a /r:n Definition Quiet mode—skips all user prompts User quite mode—shows some dialog boxes Admin quite mode—does not show any dialog boxes 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 /r:s /s Always restart—always restart the computer after the installation Silent restart—automatically restart the computer without prompting the user 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. 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.6 documentation at: http://msdn. Microsoft included bug fixes.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I represents the known switches for Microsoft patch installations.6 offer me? Now you are thoroughly interested in WSH version 5. 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. Of course. WSH 5.com/ downloads/default.microsoft. Your mileage may vary.asp?url=/downloads/sample.asp?url=/msdnfiles/027/001/728/msdncompositedoc. A service level can’t be upgraded without addressing current problems. read through the Windows Script Host 5.6.xml&frame=true. 6 .6 is quite a leap from earlier versions.

Here’s a brief overview of the new features: Security If you read the trade-rags very often. If IgnoreUserSettings is 1. What a person does with the power is up to them.VBE files have had their day in the sun as potentially dangerous email parasites. . 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.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Also.6. Remote If 1. If 0. Whether it starts as a practical joke or just a dreadfully devious person bent on the destruction of mankind. Registry Value Enabled Description If 1. The VB scripting language is so powerful that there’s very little you can’t do with it. WSH is disabled. if IgnoreUserSettings is 0 or not present. . Without special caution. then WSH is enabled. With the release of WSH 5.6. Browse through Table 2 below for full understanding of your configuration options. Default is 0 if not present. If 1. then the HKCU settings will take priority over the HKLM settings. then all scripts are run. then this machine may run scripts remotely. Microsoft included some critical configuration parameters in the form of registry key values. though the individual preference settings will still apply the user’s settings. then unsigned or untrusted 7 . you can beef up security for the scripting engines installed on your company computers. When you think about it. then the security settings will always be taken from HKLM.VBS and . included in the documentation at the noted link is a full list of the enhancements Microsoft included in version 5. just bad. anyone who can become even remotely adept at writing VB scripts could be considered a dangerous person. using VB scripting knowledge for anything but good is. 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. NOTE: In the same registry key. Some turn to “the dark side” and write scripts that can damage data. Then again. it may not. they could rear their ugly heads once again. Default is 1 if not present. well . If 0. TrustPolicy If 0. you can’t turn too many pages without a security article jumping out at you. By modifying these registry values. Security is THE hottest topic in the IT industry at the present—and rightly so. .

On WinXP: controls whether to consider the Software Restriction Policies (SRP. WinME: no effect. Win98. WinNT. The SRP settings are more thorough and robust than the simple signature checking that the TrustPolicy setting was designed for. 8 . WinME: no effect. On WinXP: controls whether to consider the Software Restriction Policies (SRP. script developers can sign their scripts to prevent unauthorized modifications. Win98. LogSecurityFailures On Win2K. then only trusted. etc. On WinXP. LogSecuritySuccesses If 1. Default is 0 if not present. Table 2 – WSH Security Registry Settings In addition to these security configuration options. you also have the option of using the SRPs—see UseWINSAFER below. signed scripts will be allowed to run. Security failures include trying to run when Enabled = 0. and administrators can enforce strict policies that determine which users have privileges to run scripts locally or remotely.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I scripts will display a prompt. Default is 1 if not present. WinNT. trying to run remotely when Remote = 0. then all security failures are entered in the event log. UseWINSAFER On Win2K. script users can now verify the authenticity of a script before running it. formerly known as WinSafer) when running scripts. Argument Handling Handling and documenting command line arguments is simpler. The SRP settings are more thorough and robust than the simple signature checking that the TrustPolicy setting was designed for. attempting to run an untrusted script when TrustPolicy = 2. and it is easier to create scripts that can supply the user with help information. Default is 0 if not present. formerly known as WinSafer) when running scripts. Default is 0 if not present. The process of integrating your scripts with other command line scripts has been simplified. warning the user that they are about to do something dangerous and giving them a chance to back out. If 2.

It’s a black-tie affair. 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.exe). be seen. Processes as Objects You determine the status of spawned processes and access their standard I/O streams. 9 . Set the Current Active Directory You can determine/modify the active process’s current working directory. She’s so excited that she’s been out every day to several different shopping centers. Frankly. you can check its progress. and your wife is expected to attend with you as your Plus One. The difference between the command-line and the Windows-based engines is only in the output — WScript. you’ve summarily forgotten this year to take your wife to a movie or even a simple dinner.exe generates windowed output. while CScript. So. The only real way to understand this difference is to see a script in action. WSH has two specific scripting engines that are used for appropriate instances. looking for just the right thing to wear. you may need to take a few days of “sick” time the following year. With so much on the line. Q: What’s the difference between WScript. and set the mode in style. 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. the one you let your wife drive? If you have to think about that too long.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Running Scripts Remotely You can load scripts onto several remote computer systems and start them all running simultaneously. You can run WSH either from the protected-mode Windows-based host (Wscript. this night out seems to her the best chance to live-it-up.exe) or from the real-mode command-shell-based host (Cscript. you can ensure that it ran correctly or determine the cause of its premature termination.exe? Friday night is the big shindig where you may receive an award for your excellent service this year.exe and CScript. Just like there’s a car for every occasion or an outfit that goes best with an event. After it has finished. While a remote script is running. due to your unflinching dedication.exe sends its output to the command window in which you started it.

as shown in Figure 3. 10 . as shown in Figure 2.Echo statements). prompts you for a specific computer name in a nice Windows box.exe Output for the Service Information Script Below is the script (notice the WScript. written for CScript.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Let’s take a look at a simple script. It then connects to the computer you specified. and then displays the output in a DOS window. This script.exe. Figure 2 – Window Prompt for a Computer Name to Query Figure 3 – Cscript. retrieves service information.

you would see a new window pop up for EVERY new line. such as the window shown in Figure 4.PathName WScript.Echo “==========================================” WScript. a window would display for EACH line you see in the figure. Figure 4 – Crazy WSH Window Meant for CScript.Echo “Service Information for “ & “”& ComputerName &”” WScript.Echo “Service State: “ & SP. .Echo “Service Name: “ & SP.Echo “Type of Service: “ & SP.Echo “==========================================” For each SP in SPSet WScript.exe.ProcessID WScript.Echo “PID: “ & SP. This output is actually a multitude of pages long. If you happened to run this script with WScript.exe 11 .InstancesOf (“Win32_Service”) WScript. If you calculate the number of services that can be installed on any given computer. that’s almost 800 windows popping up in your face every one to two seconds.Echo “==========================================” next When you look again at the information shown in Figure 2.Echo “Location: “ & SP. In addition. since the output is an enormous amount of information. The worst part . you have to hit the OK button on each Window before the script will advance. .State WScript. you can see a long list of information.ServiceType WScript. which causes the display in the DOS window to scroll for almost 30 seconds.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Service Information for CScript.Name WScript.Echo “==========================================” WScript.vbs ComComputerName = InputBox(“Enter the name of the computer you wish to query”) winmgmt1 = “winmgmts:{impersonationLevel=impersonate}!//”& ComputerName &”” Set SPSet = GetObject( winmgmt1 ). multiplied by the number of output lines for each service as defined in the script.

You would want to use the MsgBox method instead of using the Echo method. It would look something like the following script: 12 .exe Running as a Windows Process If you wanted to actually run the script with WScript. executing Windows Task Manager and choosing the Processes tab. If you somehow get duped into running a script with WScript. instead of the output in the drab DOS window.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 would only need to rewrite the WScript. Figure 5 – Wscript. and click the End Process button to exit your worst scripting nightmare. Both engines run as Windows processes. highlight it.exe to see the pretty windows. Shown in Figure 5.exe. there’s an easy way to break out of the seemingly endless loop.exe that was meant to be run with CScript. you will agree that this is time consuming and needless. you only need to search the list for the running engine.Echo section.

NOTE: When WSH is installed. it doesn’t cure it. Then.ServiceType & vbcrlf &_ “Service State: “ & SP.State Next The output would be much kinder (as shown in Figure 6). Like Superman in the 13 . either on-screen or printed on a piece of paper.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Service Information for WScript.exe is designated as the default scripting engine.ProcessID & vbcrlf &_ “Type of Service: “ & SP.exe jumps to attention and hosts the script for you.exe to host. this doesn’t have to be a permanent change! Once you change it.exe You’d probably even want to go a bit further. you may want to change the default.Pathname & vbcrlf &_ “PID: “ & SP.vbs: For each SP in SPSet MsgBox “Service Name: “ & SP.Name & vbcrlf &_ “Location: “ & SP. While this minimizes your headache somewhat. You can do this by running the following command-line: cscript//h:cscript Don’t worry. Figure 6: Service Information Output Designed for WScript. because you would still expect to see one window for every installed service. you’re not stuck with it for your entire scripting life. If you code the majority of your scripts CScript. so you can review the contents at your leisure. The best method is to pipe the output to a text file. WScript. anytime a VB script or Java script is executed. WScript.

someone got smart and started incorporating these options and arguments into a neat. There are more command-line options for both CScript.exe /? or CScript. Figure 7 – Wscript.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Bizzarro world. and Figure 7 displays CScript. by typing in the engine with the /? (WScript. You can access them the normal way. Q: What command-line options do the scripting engines offer? In the early days of computing. much like the option in the previous section to change the default scripting engine. . These options came in the form of command-line options and arguments. so then. new argument all its own. Both WScript. Figure 6 shows the command-line options for WScript. and sometimes the /help (slash-help). I cover those in the next section. WSH is no exception. a horde of commands hid spectacular options.exe and WScript. I’m not holding out on you.exe. This argument came to be called the /? (slash-question mark).exe /?). You can always change it back.exe Command-Line Options 14 . there are command-line options for the scripting engines? No.exe. it’s best to go right to the source. . the default engine-changing command has an alter ego.exe have command-line options and arguments available.exe’s options. Instead of writing out the switches for each engine. Very cool—what was once fodder for a secret society of programmers is now at your disposal to do with what you will.exe and CScript. using the following reversal command-line: cscript//h:wscript Ah . Somewhere along the line.

that there is only one difference in the command-line options: the //U switch used with CScript.exe Command-Line Options You’ll notice. There is no song and dance routine to help you decide which language is best for you. The name VBScript is taken from Microsoft’s (http://www. to deploying software. the scripting languages don’t have someone like Britney Spears to lead you in one direction or the other. to changing network passwords. JavaScript should be your tool of choice. Unfortunately.com) own Visual Basic programming language. some choose Pepsi.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Figure 8 – Cscript.sun. you come across your first conundrum: two scripting languages. I suspect more people would be interested in scripting.com/) derived the name JavaScript from the original Java language they developed. in companies that want to manage their computing and networking environment. If there was. From inventorying computer hardware. by looking between Figures 5 and 6.microsoft. Q: What are the differences between VBScript and JavaScript? When you’re just starting out. VBScript is a powerhouse for the enterprise. Sun Microsystems (http://www. If you’re working directly with web technologies.exe. Which one you use really depends on what your needs are but also what your tastes are like. VBScript is used. Some people choose Coke. 15 . JavaScript is a scripting language targeted toward web development. heading down that scripting path. primarily.

if it’s so powerful. you can “encode” a script. the file extension (. See the next FAQ for details. There’s very little difference between the full-blown programming language and the light-weight scripting language. After JavaScript has been encoded.microsoft.asp?URL=/downloads/sample. but you can’t compile script language code. but you can always come back and play with the code later on.” and “Java Jr.a sp?url=/MSDN-FILES/027/001/789/msdncompositedoc. However.jse.xml. I did say the VBScript is a powerhouse. why can’t it encode itself? It can.com/downloads/default. I hate to throw a lot of code at you in a book on VBScript basics without spending time explaining it. Since.” have many of the same functions that their Big Brothers have available.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. The major difference is that scripting languages cannot be compiled and run as standalone applications – meaning you still need WSH installed to host the script. This new file extension designation allows you to see quickly whether a script has been encoded or not. to be used as a way to increase their skill-set and to provide more value for their company and employment. You can do something similar with scripts too. All you have to do is have this script sitting somewhere in the file system. Both scripting languages are very similar to the counter-parts after which they are named.” 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. Your script is encoded automatically! 16 . once you’ve become more comfortable with the scripting languages. We call this “encoding. it can run on its own on the computer and operating system it was written for.vbs to . we won’t be discussing web development. you can compile code written with development languages. “VB Jr. and then drag and drop the script you’ve created onto it. The following will encode any script written with VBScript or JavaScript. VBScript file extensions are changed from . the scripts and script discussions in this book will be targeted at the VBScript language. An application written using a full programming language doesn’t need a host.vbe. didn’t I? Well. Compiling code for a programming language also keeps unwanted eyes from viewing and modifying the code that a programmer worked hard to create. Q: How can I protect my scripts? As outlined in the previous FAQ. Microsoft has a script encoder available for download at the following location: http://msdn.js) is changed to .

FileExists(DestPath) Then Dim DestFile 17 .GetExtensionName(SourcePath) Case “vbs” szExt = “. bstrScript. 1).vbe” Case “js” szExt = “.OpenTextFile(SourcePath.FilesystemObject”) Dim argv Set argv = WScript.” WScript. EncodedText Set enc = WScript.vbs Option Explicit Dim fso Set fso = WScript.Quit End Select Dim bstrStreamIn bstrStreamIn = fso. szExt.CreateObject(“Scripting. destExt) If Not fso.CreateObject(“Scripting. bstrStreamIn. 0.jse” Case Else MsgBox fso. Set enc = Nothing Dim DestPath DestPath = Replace(SourcePath.Quit Dim szExt.vbs” bstrScript = “VBScript” destExt = “.Arguments Dim SourcePath SourcePath = argv(0) If SourcePath = “” Then WScript.ReadAll Dim enc. destExt Select Case fso.Encoder”) EncodedText bstrScript) = enc.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Encode.js” bstrScript = “JScript” destExt = “.GetExtensionName(SourcePath) & “ files not supported in this script.EncodeScriptFile(szExt.

when you started learning how to drive a car.OpenTextFile(DestPath.html. and getting your own rhythm. 2. you won’t cause too many heart attacks.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Set DestFile = fso. Q: What’s the best way to learn to script? This question comes up quite a bit on web forums and email discussion lists. . and some code to learn how to create your own decoder here: http://www. That’s the turn signal. no. If you notice. As you are surfing the web.planet-sourcecode.6532/lngWId.Close Set DestFile = Nothing End If Set fso = Nothing Alternatively.Write Left(EncodedText. One of the most exciting aspects of the scripting community is each individual’s 18 .4/qx/vb/scripts/ShowCode. unless you write a script that reboots the file servers and test it in a production environment. whatever can be encoded can be decoded with the right utility or script. Len(EncodedText) . Some will give a long list of scripting books. . Be as script-hungry as you like.com/scrdec. and the gas pedal is on your right. . on the other side—those are the wiper blades. others will copy and paste links to their favorite scripting websites. There is no licensing fee for a script. doing your own thing. . You’re on your own. You probably gave your parents quite a few heart attacks. and no one will care. ok. every one to whom he asks this question will give a slightly different answer. No. true) DestFile.” Better than learning to drive. way back .virtualconspiracy. finding scripting websites and reviewing script code. grab it all and save it somewhere on your hard drive. What’s more. 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. When an individual finally decides that “today is the day” to start on the path to scripting.com/xq/ASP/txtCodeId. There are quite a large number of resources available to help you learn scripting. There is a freeware decoder utility available for download at the following link: http://www. . Grabbing scripts from these resources and rolling up your sleeves and just digging in is the main key to understanding the languages. Your dad gave you the basics: “You sit behind the steering wheel. learning at your own pace.1) DestFile.htm. Despite the laundry list. you won’t have to worry about needing a licensed scripter sitting in the passenger seat. The brake pedal is on your left. . one point rings through every time: you learn by doing. even further than that . he turns to those he feels would know best where to begin. Stop and remember .

com/library/ us/script56/html/vtoriVBScript.microsoft. you not only help the “newbies” get up to speed. It not only contains comprehensive information. “You mean the same company that spearheaded the effort to rid the world of product manuals?” Yep.com/downloads/default.asp Microsoft Windows Script 5.asp?url=/msdn-files/027/001/733/msdncompositedoc.6 Download— http://msdn.microsoft.myITforum.microsoft. Surely there are some websites I can give you to go on your scripting shopping spree. Don’t be stingy and keep your scripts locked up in a box somewhere. but you help keep a community growing and going strong.xml&frame=true Microsoft Windows Script 5. A quick jaunt over to Microsoft’s scripting website (http://msdn.com/library/en-us/script56/html/lettitle.a sp?url=/msdn-files/027/001/728/ msdncompositedoc. someday other people will be just like you – chomping at the bit to learn how to script.com/downloads/default. your best and most loyal companion on your scripting journey is the actual scripting documentation provided by Microsoft. here they are: MyITforum. Whether you believe it or not.com/ library/en-us/script56/html/wsoriWindowsScriptHost. the exact same.asp VBScript Documentation—http://msdn.com—http://www.microsoft. “What?” you say.6 Documentation— http://msdn. I use the documentation regularly. Well. then what? The Internet is such an enormous place.microsoft. an addition of a line or two.com/scripting) gives you the download links for all of the documentation.asp?URL=/downloads/sample .microsoft.com/ library/enus/rmscpt/Html/rmscpt.asp en- Windows Script Host Documentation—http://msdn.GETTING STARTED W I T H VISUAL BASIC SCRIPTING willingness to share what they’ve done. and a script you found or received from someone is ready to work in your environment.microsoft. though.asp Remote Scripting Documentation—http://msdn.asp?url=/downloads/sample. A couple quick changes here. By sharing the solutions you have scripted.asp JScript Documentation—http://msdn. Here’s a list of what’s available: Script Debugger Documentation—http://msdn.microsoft.microsoft.com 19 .xml When you’ve had your fill of Microsoft’s documentation.com/library/ en-us/script56/html/js56jsoriJScript. Remember.asp Windows Script Components Documentation— http://msdn. but also includes script examples in both VBScript and JavaScript that you can copy and work with yourself.com/ library/enus/sdbug/Html/sdbug_1.

It’s like reengineering a car door handle to make it more complicated. make sure to check out the VB scripting downloads area. At one point in time. Anti-virus program vendors like Symantec and McAfee have kept the fires burning late into the night. MyITforum.com is the premier website for systems administrators.net/main/ I know. This repository of scripts continues to grow.microsoft. so you’ll need to check back periodically. you can find an answer here. just because you can. The majority of the online scripting community runs through this site.com/ Another hit-and-run site for grabbing scripts. complete with script examples. There’s also a dedicated VB scripting web forum where people post problems and others post answers. Not only can you seize some free script downloads. fraught with strange web cursors and a zillion pop-up advertisements. but as a site member you can post your own solutions. that’s not the case.wshscripting. You’ll see what I mean when you visit the site.com offers a nice library of downloadable script solutions. Just typing the link into your browser address line gives you the feeling that you are being whisked away to someone’s personal homepage. This site is probably one of the first ones I found when I started out on my quest for the scripting grail. The Win32Scripting website is a well-organized library of script submissions.com/ technet/treeview/default. WSHScripting. Pure and simple. but so much effort has gone into fixing the problem that Windows scripts are now as safe as 20 . 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. Microsoft’s TechNet Script Center—http://www. Win32Scripting—http://cwashington. if you have a problem. the URL for this website is deceiving. this site is quickly becoming the epicenter for script downloads. Windows scripts were your worst enemy. 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.com has an entire article section dedicated to VB scripting with new articles posted daily.netreach.asp?url=/technet/scriptcenter/default.com—http://www.asp Recently inaugurated. There has been no formal communication as to a schedule when new scripts are released.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I MyITforum. Before you click away from the site. However. allowing you to pinpoint downloadable scripts according their topic matter. WSHScripting. I know. concocting updates to help minimize the potential damage that can be caused from unsafe scripts. The search engine is very useable. The only downfall of the website is that the navigation is a bit much and takes a while to master.

reading your email archives that date back to the dawn of the Internet. Inserting old diskettes into your disk drive. Windows 98. than a Windows script will “infect” your computer. you are as safe as you want to be. or not applying the latest Anti-virus patches—you can only blame yourself. You have to tell WSH which script engine to use. Notepad. instead of just running encode. Key = VBSFile\Shell o New Value = Edit 4. You can still run the script as a script by initiating the execution of the script. You can even further minimize your vulnerability to running unsafe or untrustworthy Windows scripts by making a simple change to the Windows registry.vbs. This is a manual way of telling WSH that it needs to do something. Windows scripts are no longer “allowed” to run unassisted. Key = VBEFile\Shell o New Value = Edit 5. which is the directory fro Windows NT.exe is normally stored in the C:\Windows directory on these computers. but you had better check to make sure. instead of running as a script. 21 . it’s probably your own fault.exe is listed as C:\WINNT\System32. and Windows XP.exe encode. These days. using the appropriate WSH engine. Associate all Windows scripts with Notepad. Key = JSEFile\Shell o New Value = Edit 2.GETTING STARTED W I T H VISUAL BASIC SCRIPTING anything is. Key = WSHFile\Shell o New Value = Edit 7. It is now more likely that a wasp will sting you. so that when a script is double-clicked or executed. For example. Key = WSHFile\Shell\Edit\command o New Value = C:\WINNT\System32\Notepad. and Windows ME computers. 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. if a virus infects your machine. The registry modification: Hive: HKEY_Classes_Root 1.exe %1 NOTE: You’ll notice that the location to Notepad. Windows 2000.vbs from a command-line. run CScript. With all of the tools available to minimize your vulnerabilities. Key = WSFFile\Shell o New Value = Edit 6. it opens in the text editor. Key = JSFile\Shell o New Value = Edit 3. You’ll need to modify that value if you want to protect Windows 95.

vbs script pasted earlier in the chapter. You can open any VB script (except for encoded scripts) in the simple text editor. and replace it with your own text. You can 22 . Notepad has some of the same features you’ll find in other script editing tools. and it helps reorganize your mind to be more in tune with the styles and formatting associated with VB scripting. Sure. and choose Edit. before you head out to the local software store or start pounding Google. you may be surprised to know that you already have everything you need to get scripting. You can Edit | Find specific text.com with search requests. The majority of the scripting community uses the simple tool included with all Windows computers—drum roll please—Notepad. I opened the Encode. By performing this action. Notepad To open or edit a script in Notepad. shown in Figure 9. After a few weeks of coding. you only need to right-click on the script. you’ll start dreaming in all black-and-white text.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Q: What tools do I need to start scripting? Chomping at the bit. Figure 9: Encode.vbs Opened in Notepad Notepad is the best tool to start with. but you can’t beat the price of Notepad. are you—trying to get your tools in place and your desktop squared away? Well. there are other tools that can maximize your scripting time by colorizing VBScript methods and routines for readability and automating specific functions.

but when your code is not quite right. You’ll be presented with the pop-up screen shown in Figure 11. Figure 11: Go to Line Command in Notepad 2. getting to line number 567 can be a problem. Figure 10: Script Error at Line 2 Character 1 The error message indicates a problem on Line 2 and in Character 1. an error message will display. Showing an error in Character 1 generally means something in the entire line is messed up. If you have an enormous script. At least you have a clear direction to start debugging though. You disable it by un-checking Word Wrap under Notepad’s Format menu. Just type in the offending line number. This extremely important feature needs to be present in any script editor to which you eventually switch. and you attempt to run your script.). Why? When you start coding you’ll understand better. giving you the line number where the error occurred (similar to the error message shown in Figure 10). Instead of counting lines. 1. do this: With Word Wrap turned off (the Go to Line command will not work when Word Wrap is enabled. and Notepad whisks you to the appropriate line straightaway. hit Ctrl-G on your keyboard. 23 .GETTING STARTED W I T H VISUAL BASIC SCRIPTING also skip to a specific line number.

programmer’s editor.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I I really couldn’t live without this great feature. On one of my searches. 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. Shown in Figure 12. you can record it once and only need to choose to use it later on. and having the Go to Line command available is a time-saver. I search periodically to see if anyone has developed a new tool for creating and editing VB scripts. but it also has a very handy Macro feature. ConTEXT I couldn’t finish off this FAQ without giving you at least a couple alternatives to Notepad. I found ConTEXT ConTEXT is a general-purpose (http://www. ConTEXT is a nice editing tool with a great interface.com/context/). Neat! 24 . allowing you to work with more than just VB scripts. and you’ll quickly find you feel the same.fixedsys. Instead of hand typing a section of code you use often. 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. giving you the ability to record repetitive tasks.

When you’re ready to move on to another scripting or programming language. ConTEXT fits the bill.hta file extension. you 25 .GETTING STARTED W I T H VISUAL BASIC SCRIPTING ConTEXT is a freeware application. These highlighter add-ons tell ConTEXT how to handle the colorization of other programming languages. 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. which you can modify to meet your needs.asp) and searching for the keyword scriptomatic. From the interface. as there are “highlighter” addons for a wide number of additional languages. 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. You can find and download this modified script. This utility is in fact. someone recently modified the WMI Scriptomatic script to connect to a Microsoft Systems Management Server and retrieve information from there. I couldn’t finish this FAQ without making mention of this great script. The WMI Scriptomatic is an example of a hypertext application. you heard me correctly. by going to the myITforum.03 MB file. 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. When executed.0 Windows resource scripts x51 Assembler WMI Scriptomatic One last recent entry to the school of automated utilities is the WMI Scriptomatic utility. the WMI Scriptomatic utility will automatically generate the VB script you need to use to pull the information from the WMI repository yourself.com/search. All it will cost you is a little bandwidth for downloading the 1.com search engine (http://www. another great script. I guess you could say it costs just a tad bit more than Notepad. In fact. You can download them all or download the specific highlighter for the job. essentially a Web page that uses a .myitforum. Yes.

WMI Essentials for Automating Windows Management. Figure 13: WMI Scriptomatic Utility Creating Script for Serial Port Information NOTE: For the best information on WMI and WMI scripting. You can only play scripting Solitaire for so long. Granted. start looking at you strangely (maybe more strangely than they do now). but people will. Besides.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I can Save the script or Run the script. eventually. all without leaving the comfort of the GUI. that could prove to be a lot of fun. by Marcin Policht. pick up the book. what good is a management tool without the ability to use it across all computers in the company? 26 . 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.

or some other method you 27 . you can utilize that power anytime you want. You can offer the link through an email. that’s just crazy. a login script. "\\server\share" net. 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. Dim net Set net = CreateObject("WScript. "\\server\share" Network Share VB script works like any other application or program that executes on a local computer. and offer a link to run the script. 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. With just a few lines of code. Login scripts allow network administrators to send instructions to the remote computer each time it logs onto the network. some extreme knowledge of VB scripting is required.Network") net. 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. it may make better sense. but it can be done and easily. If you remember how powerful VB script is. realizing that if you have replaced your login scripts with VB scripts.MapNetworkDrive "Q:". you can provide these network drive mappings. you say. This “codelet” simply maps the network drives O and Q for the computer logging into the network. Some companies have even replaced their login scripts completely with VB scripts! OK. instead of searching the Internet for a freeware tool that will work in your environment. 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. Granted. Just plop the script on the network.MapNetworkDrive "O:".GETTING STARTED W I T H VISUAL BASIC SCRIPTING VBScripts can run on remote computers in a few different ways.

. VB scripts run great from web pages—either through a link that executes the script. You just sit in the comfort of your cubicle. it makes sense to understand that if you can get the script to the remote computer. SysInternals offers a slew of freeware utilities geared toward aiding the systems administrator. Using any method you currently employ. Run on Remote Computer Since VB scripts can run flawlessly on a local computer. 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. and the remote computer executes your commands. VB scripts work just fine using a hard-coded drive letter or a UNC path. Some go even farther by providing software downloads and installations. just run from yours. type out a few instructions on your keyboard. or a component that runs the script when a specific web page is loaded into the computer’s web browser. so there’s no overhead on the remote computer. it will run.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I personally utilize to get software to the end-user. this is where you would hear an evil laugh emanate—Bwahahahaha . One of the more popular tools in this area is from SysInternals. Remote Execution Utility Several utilities on the market allow you to execute programs on remote computers. Websites are a great tool for company communications. If you’ve watched many horror movies with a mad dictator or scientist. . It doesn’t need to be installed 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 -p Specifies optional user name for login to remote computer Specifies optional password for user name—if you omit this you will be prompted 28 . PsExec is the utility that allows remote execution of commands/programs. Web Page More and more companies utilize some kind of internal website for offering company information.

you must first set up the remote machine with the proper security settings. Copy the specified program to the remote system for execution. Run the program so that it interacts with the desktop on the remote system. even if the file already exists on the remote system. -f Copy the specified program to the remote system. -s -i -c Run remote process in the System account. program arguments Name of the program to execute Arguments to pass—note that file paths must be absolute paths on the target system.shtml. then the application must be in the system's path on the remote system. With Remote WSH. Only use this option for non-interactive applications. the script is physically copied from the local machine to the remote machine before executing. -d Don't wait for application to terminate. you didn’t think Microsoft would sit idly back and not supply this functionality in WSH. It provides the ability to run a script on a remote machine or machines. did you? Not likely.com/ntw2k/freeware/psexec. 29 . Remote WSH is a new technology included in WSH 5.sysinternals. NOTE: Both the remote and local machines must be running Windows NT 4 SP3 or greater in order to use Remote WSH. If you omit this option. You can download PsExec from the following location on SysInternals’ website: http://www. sound technology you can expect Microsoft to incorporate it eventually.6.GETTING STARTED W I T H VISUAL BASIC SCRIPTING to enter a hidden password. Remote WSH With the remote execution utilities on the market. In order to enable Remote WSH functionality. If it’s a good.

adm policy file.6 has already been installed.6 is available for download from the web at http://msdn. Add yourself to the remote machine’s Local Administrators group.hitentertainment.microsoft. Hey. NOTE: WSH 5. Install WSH V5. use the System Policy Editor (Poledit.6 on the machine. If not.exe) on the computer to incorporate the windowsscript.com/scripting to acquire the necessary windowsscript.exe’s online help system. it would go something like 30 . My youngest has been singing it since he was much younger than he is now. For a VB scripter. blah. If you are using Windows XP or have installed Internet Explorer 6 or greater. 3. then you know Bob the Builder.com/scripting.microsoft.exe. you need to get “with it” (http://www. WSH 5. this is nonetheless where the default adm files are located.adm file that contains the WSH settings.adm file must be copied to the computer that sets the applicable group’s policies. WSH should now be enabled on the machine. 2. blah ADDITIONAL NOTE: For more information on Poledit. The windowsscript. 4. NOTE: An administrator who wants to enable Remote WSH must either acquire the Windows 2000 resource kit or use http://msdn.com/bobthebuilder/). I need to override Word’s blah. To enable Remote WSH. I n eed a little help here.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Setting-Up Remote WSH 1. Poledit. see the Poledit. Although it is not necessary to copy the file to the server’s \WINNT\INF directory. Q: Can I retrieve remote information from my computer? If you have kids. There’s a little jingle that goes with the kids’ program.exe can be run from the Start| Run command.

the Manufacturer of the computer. There are lots of administrators who aren’t aware of the data contained on a computer. 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. 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) 31 . you can utilize VB scripts to connect to a remote computer and pull information about that computer. the script first prompts you for the name of the computer from which you want to extract the serial number. To make it simple. The WMI database structure is broken down into Classes with Properties full of data. WMI. allowing you to get information about the installed BIOS options (which. there’s a Computer class (Win32_ComputerSystem) which stores information (Properties) about the local computer. which stands for Windows Management Instrumentation. is a computer data storehouse accessed easily with VBScript. Each computer stores a significant amount of data about itself. Much like an application can query a SQL database for data. you don’t need to set up Remote WSH to do it. except the WMI repository is filled with data automatically. Don’t worry – you won’t be kicked out of the Geek club and marked for life with the word “EndUser” stamped on your forehead. incidentally. such as the Current Time Zone. so don’t feel bad if you’re just hearing about this. Believe it or not. The following “handshake” connects to the computer BIOS class on a remote computer. and the Domain that the computer belongs to. This data is stored in the WMI repository. The WMI repository works similarly to an SQL database.GETTING STARTED W I T H VISUAL BASIC SCRIPTING this: “Can we do it? YES WE CAN!” And. contains the serial number of the computer). For example.

Remember. Look at the following table for a sampling of what you can find in the BIOS class alone: Property BiosCharacteristics Description BIOS characteristics supported by the system as defined by the System Management BIOS Reference Specification 32 .JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I winmgmt1 = "winmgmts:{impersonationLevel=impersonate}!//"& ComputerName &"" Once you’ve made the connection. There is so much information stored in WMI that it will boggle your mind. . ‘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. Not only that. this is just one class in WMI. you dig even further by getting the data out of the Serial Number property. you only need to query the properties of the BIOS class: ‘Connecting to the BIOS class Set SNSet = GetObject( winmgmt1 ). there is a horde of other properties. .InstancesOf ("Win32_BIOS") Then.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. what good is data if you can’t .

ListOfLanguages Manufacturer Name PrimaryBIOS List of names of available BIOS-installable languages Manufacturer of this software element Name used to identify this software element 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. InstallDate When the object was installed—a lack of a value does not indicate that the object is not installed. Degraded. Operational statuses include OK. may be functioning properly but 33 .GETTING STARTED W I T H VISUAL BASIC SCRIPTING CurrentLanguage Description IdentificationCode Name of the current BIOS language Description of the object Manufacturer's identifier for this software element—often this will be a stock keeping unit (SKU) or a part number.MMMMMM(+)OOO. (An element. SerialNumber SMBIOSBIOSVersion SMBIOSMajorVersion Assigned serial number of the software element BIOS version as reported by SMBIOS 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. and Pred Fail. such as a SMART-enabled hard drive. SMBIOSPresent Indicates whether the SMBIOS is available on this computer system Status Current status of the object—various operational and nonoperational statuses can be defined.

certain computer requirements must be met.microsoft. Not all such work is on-line. Unknown. WMI 1.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I predicting a failure in the near future).com/library/default. Your computer’s BIOS must support a special industry standard called SMBIOS. Starting. Pred Fail.dmtf.1 or better. check with the computer's manufacturer. and Service. 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). yet the managed element is neither OK nor in one of the other states. Degraded. If you are curious if your computers are SMBIOS compliant. Values are OK. You’ll be able to locate the WMI SDK download at the following Microsoft MSDN web page: http://msdn. and Service. or other administrative work. TargetOperatingSystem Version Target operating system of the owning software element Version of the BIOS—this string is created by the BIOS manufacturer.5 or better is the requirement. NOTE: For certain functions (like obtaining serial numbers). reload of a user permissions list. Stopping. but there’s a huge amount of information included in the WMI SDK that is extremely useful to VB scripters. see the Desktop Management Task Force (DMTF) website: http://www. For more information on SMBIOS.asp. A specific version of WMI is required on each computer from which you want to retrieve the serial number.org. Error. I realize this sounds like a programmer’s tool. The latter could apply during mirror-resilvering of a disk. Non-operational statuses include Error. Starting. Stopping. 34 . and the version number must be compatible with 2.asp?url=/library/enus/wmisdk/wmi/ wmi_start_page.

Echo Provider. Microsoft developed common “connectoids” called providers for many of their servers. each provider includes a namespace or a number of namespaces. 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://. the song is probably stuck in your head.Name Next Some common providers and namespaces: Provider ADSI NameSpace LDAP Description This namespace implementation is compatible with Lightweight Directory Access Protocol (LDAP). An example is the ADSI Service Provider. Run the following on any computer to retrieve the list of available providers: Set objProvider = GetObject("ADs:") For Each Provider In objProvider WScript. you can!” Sorry. 35 . and to give better abilities to developers. To make it easier to access specific Microsoft server offerings. that was another Bob the Builder reference. Then.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Q: Can I query information for other things— like SQL Server? “Yes./root/MicrosoftSqlServer") You can actually get a list of the providers available on a given system with— what else—a VB script. If you’ve taken the time to visit the website. too.) As an example. which includes several namespaces (shown in the table in this section.

Will VB scripts work without this special formatting? You bet. Organization is the last thing on their minds. but it will work. they are formatted a specific way.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I ADSI ADSI ADSI WMI WinNT NDS NWCOMPAT Winmgmts This namespace implementation is compatible with Windows NT®/Windows® 2000. and oodles of doodles of Bill Gates and Steve Ballmer sitting on mounds of cash.x. Well. How much easier it would be if you put all socks in a drawer by themselves. . This namespace implementation is compatible with Novell NetWare 3. a dozen broken stress relief balls. past your shirts. and that’s not just talking about their workspaces littered with Mountain Dew bottles. As long as you follow the guidelines for creating your script. commented out to save to work on later. A programmer’s code can be a mess of strings. you can always jump back quickly to troubleshoot or to add new variables. Script formatting is similar to this scenario. I hope you’re realizing that VB script is a mighty powerful tool. . Look at the following. 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. . . It shows a series of variables. and you want to find a single pair of socks. Is that a clear answer? Programmers can be the messiest bunch of people on the planet. This namespace implementation is compatible with Novell NetWare Directory Service (NDS). Q: In VB scripts I’ve seen. and Yes. Most scripters initialize their variables at the very beginning of their scripts. initialized at the beginning of the script. You have to dig through the entire drawer. and in between your pant legs. 36 . You can use variables initialized here throughout the entire script. If you define all of your variables in one area of the script. Think about it . say you stuff all of your laundry into one drawer. Is this important? No . just to locate a pair of socks to wear. under you underwear. It may be the messiest looking bit of chicken scratch. the script will function. it’s also a big benefit for anyone else wanting to understand and possibly modify your script later on. The special formatting is strictly for your benefit. the scripter.

it skipped it. no colon is needed. In the old DOS batch file days. As a simple suggestion. Q: Can I add comments to my scripts? If you’ve ever scripted anything before. the colon is not required.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Dim Dim Dim Dim Dim Dim Dim Dim colProcesses refProcess refWMI strMoniker strQuery numLow numHigh i The formatting doesn’t even have to end there. Using the remark statements. An apostrophe (‘) can be used anywhere. This goes a long way toward organizing the script text. you should comment the heck out of your code. When the batch compiler saw the REM. ‘ Comment on a line with no code. as well as helping you remember what a specific section of the script is doing in the overall scheme of things. you could use the REM (remark) statement to add comments. Used on a line by itself. You can use special characters to document your script. VB script has this type of function available. as well as the apostrophe (‘) character. and that includes the old REM standby. MyStr2 = needed. input as much information about your script as 37 . there’s a bit more to it than that. However. Does it sound confusing? Try this: MyStr1 = "Hello" : REM Comment after a statement separated by a colon. you know how useful it is to make comments in your scripts. I discuss that in the next Question. "Goodbye" ‘ This is also a comment. no colon is needed. you must separate the REM statement and the code with a colon (:). If you use the REM statement on a line that contains other code. no colon is REM Comment on a line with no code.

Q: Can I use VBScript to send keystrokes to Windows? The SendKeys function of VBScript would have made for an interesting X-Files episode. You can also send any letter or number available on the computer’s keyboard.asp. I have heard excellent comments on them.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I possible.com/traincert/default.microsoft. The SendKeys function of VBScript probably one of the most popular functions. You could write an 38 . You can actually send keystrokes to the Windows shell. Sure. 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. You’ll thank yourself later. Moulder decides it’s the work of technology obtained through the Roswell crash of 1947. or input text. Microsoft currently offers two courses for those interested in getting hands-on training for VB scripting. it takes a bit more time and feels like a pain. allowing you to automatically click through dialog boxes. Course Number 2433AC 2439AC Course Description Visual Basic Script and Windows® Script Host Essentials Scripting Microsoft® Instrumentation Windows® Management 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. especially when you’re working feverishly on a new code solution. Maybe it’s just the systems administrator using VBScript to harass the enduser population. Q: Does Microsoft have any official curriculum for VB script? While I’ve not attended these courses myself. Scully tries to convince Moulder that there has to be a scientific reason behind it. but the benefits definitely outweigh the time you lose initially. He goes on to prove that the systems administrator is actually the only survivor of the Roswell saucer crash.

To send these kinds of keystrokes. CTRL. or {BKSP} BREAK {BREAK} CAPS LOCK {CAPSLOCK} DEL or DELETE {DELETE} or {DEL} DOWN ARROW {DOWN} F4 {F4} END {END} F5 {F5} ENTER {ENTER} or ~ F6 {F6} ESC {ESC} F7 {F7} HELP {HELP} F8 {F8} HOME {HOME} INS or INSERT {INSERT} or {INS} LEFT ARROW {LEFT} F11 {F11} NUM LOCK {NUMLOCK} F12 {F12} PAGE DOWN {PGDN} F13 {F13} PAGE UP {PGUP} F14 {F14} PRINT SCREEN {PRTSC} F15 {F15} RIGHT ARROW {RIGHT} F16 {F16} SCROLL LOCK {SCROLLLOCK} F9 {F9} F10 {F10} TAB {TAB} UP ARROW {UP} F1 {F1} F2 {F2} F3 {F3} To send keyboard characters that are comprised of a regular keystroke in combination with a SHIFT. send the arguments shown in the following list: BACKSPACE {BACKSPACE}. Some keystrokes represent actions (such as BACKSPACE and BREAK). Some keystrokes do not generate characters (such as ENTER and TAB). but that ability exists. 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: 39 . {BS}.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. or ALT.

SendKeys "~" WScript.GETTING STARTED W I T H VISUAL BASIC SCRIPTING SHIFT + CTRL ^ ALT % Example 1: MS Calculator Automation The following SendKeys example.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: .SendKeys "~" WScript.SendKeys "2" WScript.CreateObject("WScript.Sleep 100 WshShell.Sleep 500 WshShell.Shell") WshShell.Run "calc" WScript.AppActivate "Calculator" WScript.Sleep 500 WshShell.Sleep 500 WshShell.Sleep 500 WshShell.SendKeys "1{+}" WScript. runs MS Calculator and sends keystrokes to make a calculation.Sleep 100 WshShell.SendKeys "*3" WScript. set WshShell = WScript.

NOTE: A couple other available technologies send keystrokes with which you might already be familiar. One of the precursors to VBScript was the ScriptIT language (also from Microsoft).microsoft.com). There are many software delivery mechanisms available. and when appropriate.Shell") WshShell. monitor the window titles of active processes.asp). send a set of keystrokes to the correct window. AutoIT is a simple scripting language that can be found at http://www. AutoIT is one of these technologies.altiris. 1.com/windows2000/techinfo/howitworks/management/i 41 . such as Microsoft Systems Management Server (http://www. and Windows 2000 and 2003 Server Intellimirror (http://www.Shell") WshShell.microsoft. This tool can be used to start a process. this may be an option for you. You can find more information on ScriptIT on this Microsoft website: http://www.hiddensoft.com/ntserver/techresources/deployment/NTserv er/scriptit3. ScriptIT is a tool for automating interactive software installations and system configuration tasks.microsoft.SendKeys "{NUMLOCK}" “Pretty neat. That’s not to say that VBScript can’t initiate the installation of software.” you might say.com/smserver/default. just that it provides no “mechanism” for getting the software to the computers in your company.SendKeys "{CAPSLOCK}" Example 3: Turning Num Lock On and Off This example turns the Num Lock key on and off: set WshShell = CreateObject("WScript. offerings from Altiris (www. and you’d be right.asp 2.GETTING STARTED W I T H VISUAL BASIC SCRIPTING set WshShell = CreateObject("WScript. You can use these scripting tools either alone or with VBScript. and if you’re not too keen on delving too deeply into VBScript.com/AutoIT. Q: Can I deliver software with VBScript? Software delivery requires a mechanism.

LPT3. You can modify the path statement following the Explorer.Network") WshNetwork. how would you like to be able to target all Windows XP computers. control software licensing. from the software delivery aspect. Particularly.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 settle for a VBScript-only solution for delivering software. For example. Think of it in terms kitchen appliances. You can interact with printers by adding or removing printer connections or by getting a specific printer’s properties. be able to distribute software based on a schedule like: only deliver the software to a specific group of computers. but the toaster oven can do so much more. etc.asp). You just need to know how to code a script to kick-off the installation of an application.CreateObject("WScript.exe command to tweak the command to open in any folder you like. a systems management application can offer some comprehensive features that “manual” solutions can’t offer. Dim oWSHShell Set oWSHShell = WScript. LPT1 is the specified port. COM1. In this example.Run command. You can modify this to LPT2. etc. The following script uses the WSHShell.RemovePrinterConnection "LPT1:" 42 . Both can toast bread.exe and to open with the C:\WINNT directory as the initially displayed folder.CreateObject("WScript. Set WshNetwork = WScript. 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.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I ntellimirror. You can even utilize web pages and login scripts as a mechanism. next Tuesday at 3:00am? VBScript works with each of these systems management mechanisms. COM2.Run "Explorer. support users remotely. You have a toaster on one hand and a toaster oven on the other. or you can utilize a full systems management application to deliver software. and that meet the application’s RAM and video requirements? Or.Shell") oWSHShell. inventory the hardware and software of the company’s equipment. (essentially any supported printer port). with enough hard disk space. to run Explorer.

AddPrinterConnection "LPT1". In the example below.GETTING STARTED W I T H VISUAL BASIC SCRIPTING Adding a Printer Connection By utilizing the WSH network component. There is a horde of printer data you can retrieve just be accessing the Win32_Printer section of the WMI repository. you can add a network-defined printer to any available port on the computer. as well as the server and print queue information (\\Server\Print1). Look at the following information. and how much data you want to retrieve. Set WshNetwork = CreateObject("WScript. change the port (LPT1) to the port you require. Attributes: AveragePagesPerMin ute: Comment: Availability: Caption: AvailableJobSheets: CharSetsSupported: ConfigManagerErrorCode: ConfigManagerUserConfi g: CreationClassName: CurrentLanguage: CurrentPaperType: DefaultCopies: DefaultNumberUp: Description: CurrentCapabilities: CurrentMimeType: Default: False DefaultLanguage: DefaultPaperType: DetectedErrorState: CurrentCharSet: CurrentNaturalLanguage: DefaultCapabilities: DefaultMimeType: DefaultPriority: DeviceID: 43 . data for printers are no exception. Well. \\Server\Print1 Getting Printer Properties We talked about WMI earlier and the amount of data this repository provides. It just depends on what you want information about.Network") WshNetwork. which represents a VBScript querying all of the printer properties available in WMI.

and they always have been.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Direct: EnableBIDI: ErrorDescription: DoCompleteFirst: EnableDevQueryPrint: ErrorInformation: DriverName: ErrorCleared: ExtendedDetectedErrorSt ate: ExtendedPrinterStatus: InstallDate: LanguagesSupported: Location: MaxNumberUp: Name: PaperTypesAvailable: PortName: Hidden: JobCountSinceLastReset: LastErrorCode: MarkingTechnology: MaxSizeSupported: NaturalLanguagesSupported: Parameters: PowerManagementCapabilitie s: HorizontalResolution: KeepPrintedJobs: Local: True MaxCopies: MimeTypesSupported: Network: PNPDeviceID: PowerManagementSuppo rted: PrintJobDataType: Published: SeparatorFile: ShareName: Status: SystemName: VerticalResolution: PrinterState: PrintProcessor: Queued: ServerName: SpoolEnabled: StatusInfo: TimeOfLastReset: WorkOffline: PrinterStatus: Priority: RawOnly: Shared: False StartTime: SystemCreationClassName: UntilTime: Table 6 – Printer Properties Available in the WMI Repository Installing Printers Printer installations are a pesky prospect. 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. it’s usually best to just use the vendor’s printer installation files. Because of the way a printer installation interacts with the computer at the hardware level. 44 .

PrintUI.PrintUIEntry /? When this command runs. the following dialog box is displayed.dll Options Utilizing the new functionality of PrintUI.dll file by typing the following in the Start | Run dialog box: rundll32 printui. You can view all of the options available to you through the PrintUI. 45 . the following VB script creates a printer connection. installs the printer to the printers folder. allowing you to review the options: Figure 17 – PrintUI. and you can access the functions with a single set of command line options. When the script runs. it prompts for the UNC to the server and printer share. and makes it the default printer.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.dll contains the functions that post Windows 2000 computers use when installing printers.DLL.dll.

You can’t turn back now.dll switches to install the printer. Dim p p = InputBox("Enter the network path to the printer you want to install:". you will be stuck at the base of the mountain forever. your plight in life will become nothing more than their roadside scenery. 46 . or even months.CreateObject("WScript. True enlightenment can be obtained by treading onward. and finally. your journey has already started.Shell"). "Add Printer". By picking up this book and perusing through it. enterprise scripting will ultimately become a requirement for employment. using the basics as a foundation. you will meld into the blur of the rushing landscape. Reading and remembering the basics outlined in this book gives you a solid foundation to construct a good working knowledge of scripting. a new talent. As more and more people wear down their soles on the Geek highway. It is a stepping-stone in the evolution of a new career. picking up pieces here-and-there. VB scripting is more than just a momentary fascination. "\\Server\PrinterName") If p <> "" Then Dim cmd cmd = "rundll32 printui.PrintUIEntry /in /n" & p WScript. As their speed picks up. reusing the code. If you do. In the coming years. or of advancement to a higher level. it runs the proper PrintUI. downloading code and figuring out what it’s doing and how it’s doing it.JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I Figure 18 – Prompting for Network Path and Printer Then. What a profound statement.Run cmd End If Summary Someone once said that your journey begins with your first step.

His columnist homepage can be located at: http://www..Publisher: Microsoft Press.com/contrib/default.myitforum.asp?cid=894 Microsoft Windows 2000 Scripting Guide Author: The Microsoft “Scripting Guys”.com. ISBN: 0-672-32144-0 Marcin also writes articles on WMI for myITforum..GETTING STARTED W I T H VISUAL BASIC SCRIPTING R E S O U R C E S WMI Essentials for Automating Windows Management Author: Marcin Policht. Torres. ISBN: 0-7356-1867-4 Windows Admin Scripting Little Black Book 2nd Edition Author: Jesse M.Publisher: SAMS.Publisher: Paraglyph Publishing.. ISBN: 1932111875 47 .

Sign up to vote on this title
UsefulNot useful