0% found this document useful (0 votes)
168 views50 pages

Just The FAQs To VB Scripting Basics

Windows Script Host (WSH) allows Windows computers to run scripts written in Visual Basic Scripting and JavaScript. It is the component that hosts Windows scripting functions. The latest version of WSH is 5.6, which can be downloaded from Microsoft's website. It is recommended to always use the latest version of WSH since it contains bug fixes and new features while maintaining backward compatibility. WSH can be deployed using various methods like login scripts, batch files, or deployment tools. The installer executable is called Scripten.exe and has options to control the installation process.

Uploaded by

viswabharani
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views50 pages

Just The FAQs To VB Scripting Basics

Windows Script Host (WSH) allows Windows computers to run scripts written in Visual Basic Scripting and JavaScript. It is the component that hosts Windows scripting functions. The latest version of WSH is 5.6, which can be downloaded from Microsoft's website. It is recommended to always use the latest version of WSH since it contains bug fixes and new features while maintaining backward compatibility. WSH can be deployed using various methods like login scripts, batch files, or deployment tools. The installer executable is called Scripten.exe and has options to control the installation process.

Uploaded by

viswabharani
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Just the

FAQs

to Understanding

VBScripting Basics
Part I: Getting Started with Visual Basic (VB) Scripting
SUPER-GEEK, STEP IOR, GETTING TO THE MOUNTAIN

Rod Trent

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

uch of your life, youve 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, youve 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 (hmmmor maybe its just that you are being tolerated because they now NEED you), Windows Script Host entered your life. You cant quite put your finger on the feeling, but its as if destiny has arrived. Windows Script Host is the key youve been looking for. Like a burning ember on a mountain in view, fulfillment and redemption are just a hardened climb away. In this book, youll 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 spouses 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 youve seen on television or in the movies. Either one, you have latched onto a universal topic that has no wrong answer, two, youre 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. Id 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, Im a social outcast. To me, following rules like that is too much effort. Id rather have the knowledge beforehand that would enable me to interact intelligently. If youre like me (and I suspect you are, since youre 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 dont laugh silently. They laugh right to your face and laugh so loud that the entire room shifts their attention to your location. If youre 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. Its the horse to the cart; the footman to the rickshaw; the feet to the Flintstone-mobileyou 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 cant react. You may have the most glorious VB script, worthy of a years 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 80s 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.

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

EXTRA NOTE: For those too young or too cool to remember MacGyver, look at this link: http://www.jumptheshark.com/m/macgyver.htm.
As amazing as that show was (groan), WSH is very much the MacGyver of the Windows computing environment. A better question might be, What cant I do with WSH? WSH is ideal for logon scripting, administrative scripting, and machine automation. Youll understand further just how powerful WSH is as you read through the rest of the book, but heres 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 its too outdated to play MP3 CDs. Having that kind of functionality is a home theater pundits 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.

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

Okay, to better answer which version of WSH you need, lets just say its 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, isnt 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 youre 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 Microsofts 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.

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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

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 doesnt 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 doesnt 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 computers memory is flushed through a reboot. Then, why arent these additional switches readily available in the installation Help screen? Thats a very good questionone that I myself will ask when I can pinpoint the correct person. Until then, the following table (Table 1)

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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

Switch /q /q:u /q:a /r:n

Definition Quiet modeskips all user prompts User quite modeshows some dialog boxes Admin quite modedoes not show any dialog boxes Never restartdo not restart the computer even if it is necessary to complete the installation

/r:i

Restart if necessaryautomatically restart the computer if it is necessary to complete the installation

/r:a /r:s /s

Always restartalways restart the computer after the installation Silent restartautomatically restart the computer without prompting the user Silent modesome programs use this switch instead of the /q switch to install in quiet mode

/n:v

No version checkinginstalls 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 cant 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 wasnt 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=/msdnfiles/027/001/728/msdncompositedoc.xml&frame=true.

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

Also, included in the documentation at the noted link is a full list of the enhancements Microsoft included in version 5.6. Then again, why should you immediately jump out to a webpage to read a document when youre totally engrossed in this book? Theres no need. Heres a brief overview of the new features:

Security
If you read the trade-rags very often, you cant turn too many pages without a security article jumping out at you. Security is THE hottest topic in the IT industry at the presentand 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 theres very little you cant 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 users settings.

Registry Value Enabled

Description 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

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

scripts will display a prompt, warning the user that they are about to do something dangerous and giving them a chance to back out. If 2, then only trusted, signed scripts will be allowed to run. On WinXP, you also have the option of using the SRPssee 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.

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. 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 processs current working directory.

Q: Whats 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. Its a black-tie affair, and your wife is expected to attend with you as your Plus One. Frankly, due to your unflinching dedication, youve 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. Shes so excited that shes 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 daythe same one that has McDonalds coffee stains in the passenger seator 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 theres 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.

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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

10

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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, thats 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

11

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

Unless youre 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, theres 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:

12

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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

Youd 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 doesnt 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

Dont worry, this doesnt have to be a permanent change! Once you change it, youre not stuck with it for your entire scripting life. Like Superman in the

13

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

Bizzarro world, the default engine-changing command has an alter ego. You can always change it back, using the following reversal command-line: cscript//h:wscript Ah . . . so then, there are command-line options for the scripting engines? No, Im 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 coolwhat 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, its best to go right to the source. Figure 6 shows the command-line options for WScript.exe, and Figure 7 displays CScript.exes options.

Figure 7 Wscript.exe Command-Line Options

14

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

Figure 8 Cscript.exe Command-Line Options

Youll 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 youre 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 dont 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 youre 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 Microsofts (http://www.microsoft.com) own Visual Basic programming language.

15

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

NOTE: We have written this book for those individuals who want to add scripting to their IT tool belt, to be used as a way to increase their skill-set and to provide more value for their company and employment. Since, we wont 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. Theres 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 standalone applications meaning you still need WSH installed to host the script. An application written using a full programming language doesnt 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 cant 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.a sp?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, didnt I? Well, if its so powerful, why cant 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 youve 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 youve created onto it. Your script is encoded automatically!

16

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

Encode.vbs
Option Explicit Dim fso Set fso = WScript.CreateObject(Scripting.FilesystemObject) Dim argv Set argv = WScript.Arguments Dim SourcePath SourcePath = argv(0) If SourcePath = Then WScript.Quit Dim szExt, bstrScript, destExt Select Case fso.GetExtensionName(SourcePath) Case vbs szExt = .vbs bstrScript = VBScript destExt = .vbe Case js szExt = .js bstrScript = JScript destExt = .jse Case Else MsgBox fso.GetExtensionName(SourcePath) & files not supported in this script. WScript.Quit End Select Dim bstrStreamIn bstrStreamIn = fso.OpenTextFile(SourcePath, 1).ReadAll Dim enc, EncodedText Set enc = WScript.CreateObject(Scripting.Encoder) EncodedText bstrScript) = enc.EncodeScriptFile(szExt, bstrStreamIn, 0,

Set enc = Nothing Dim DestPath DestPath = Replace(SourcePath, szExt, destExt) If Not fso.FileExists(DestPath) Then Dim DestFile

17

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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-sourcecode.com/xq/ASP/txtCodeId.6532/lngWId.4/qx/vb/scripts/ShowCode.htm.

Q: Whats 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. Thats the turn signal. No, no, on the other sidethose are the wiper blades. Better than learning to drive, you wont have to worry about needing a licensed scripter sitting in the passenger seat. Youre on your own, doing your own thing, learning at your own pace, and getting your own rhythm. Whats more, unless you write a script that reboots the file servers and test it in a production environment, you wont 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 individuals

18

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

willingness to share what theyve 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. Dont 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 Microsofts scripting website (http://msdn.microsoft.com/scripting) gives you the download links for all of the documentation. Heres a list of whats available: Script Debugger Documentationhttp://msdn.microsoft.com/ library/enus/sdbug/Html/sdbug_1.asp Remote Scripting Documentationhttp://msdn.microsoft.com/ library/enus/rmscpt/Html/rmscpt.asp JScript Documentationhttp://msdn.microsoft.com/library/ en-us/script56/html/js56jsoriJScript.asp VBScript Documentationhttp://msdn.microsoft.com/library/ us/script56/html/vtoriVBScript.asp en-

Windows Script Host Documentationhttp://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.a sp?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 youve had your fill of Microsofts 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.comhttp://www.myITforum.com

19

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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. Theres 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. Microsofts TechNet Script Centerhttp://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 youll need to check back periodically. WSHScripting.comhttp://www.wshscripting.com/ Another hit-and-run site for grabbing scripts, WSHScripting.com offers a nice library of downloadable script solutions. Win32Scriptinghttp://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 someones personal homepage, fraught with strange web cursors and a zillion pop-up advertisements. However, thats 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. Its like reengineering a car door handle to make it more complicated, just because you can. Youll see what I mean when you visit the site.

Q: Arent 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

20

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

anything is. It is now more likely that a wasp will sting you, than a Windows script will infect your computer. With all of the tools available to minimize your vulnerabilities, you are as safe as you want to be. These days, if a virus infects your machine, its 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 patchesyou 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: Youll 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. Youll need to modify that value if you want to protect Windows 95, Windows 98, and Windows ME computers. Notepad.exe is normally stored in the C:\Windows directory on these computers, but you had better check to make sure.

21

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

Q: What tools do I need to start scripting?


Chomping at the bit, are youtrying 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 computersdrum roll pleaseNotepad. 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 cant 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, youll start dreaming in all black-and-white text. Notepad has some of the same features youll find in other script editing tools. You can Edit | Find specific text, and replace it with your own text. You can

22

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

also skip to a specific line number. This extremely important feature needs to be present in any script editor to which you eventually switch. Why? When you start coding youll 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: 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 Notepads Format menu.), hit Ctrl-G on your keyboard. Youll be presented with the pop-up screen shown in Figure 11.

1.

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.

23

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

I really couldnt live without this great feature, and youll quickly find you feel the same. I cant think of a single script Ive written where I didnt 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 couldnt 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 ConTEXT is a general-purpose (http://www.fixedsys.com/context/). programmers 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 Programmers 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!

24

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

ConTEXT is a freeware application. All it will cost you is a little bandwidth for downloading the 1.03 MB file. I guess you could say it costs just a tad bit more than Notepad. When youre ready to move on to another scripting or programming language, ConTEXT fits the bill, as there are highlighter addons 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 couldnt 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 computers 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. Hows that for writing your first scripts? Figure 13 shows the WMI Scriptomatic utility being used to build a script to pull information about the computers serial port hardware. From the interface, you

25

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

can Save the script or Run the script, all without leaving the comfort of the GUI.

Figure 13: WMI Scriptomatic Utility Creating Script for Serial Port Information

NOTE: For the best information on WMI and WMI scripting, pick up the book, WMI Essentials for Automating Windows Management, by Marcin Policht.

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?

26

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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, thats 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 its not surprising that you can place a VB script on a network share that users have access to and have them run the script in some way. Just plop the script on the network, and offer a link to run the script. You can offer the link through an email, a login script, or some other method you

27

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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

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 pageseither through a link that executes the script, or a component that runs the script when a specific web page is loaded into the computers web browser.

Remote Execution Utility


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 youve watched many horror movies with a mad dictator or scientist, this is where you would hear an evil laugh emanateBwahahahaha . .. 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 doesnt need to be installed on the remote computer, just run from yours, so theres 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 -p

Specifies optional user name for login to remote computer Specifies optional password for user nameif you omit this you will be prompted

28

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

to enter a hidden password.


-s -i -c Run remote process in the System account. Run the program so that it interacts with the desktop on the remote system. 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 arguments Name of the program to execute Arguments to passnote 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 didnt think Microsoft would sit idly back and not supply this functionality in WSH, did you? Not likely. If its a good, sound technology you can expect Microsoft to incorporate it eventually. Remote WSH is a new technology included in WSH 5.6. It provides the ability to run a script on a remote machine or machines. With Remote WSH, the script is physically copied from the local machine to the remote machine before executing. In order to enable Remote WSH functionality, you must first set up the remote machine with the proper security settings.

NOTE: Both the remote and local machines must be running Windows NT 4 SP3 or greater in order to use Remote WSH.

29

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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. 3. Add yourself to the remote machines Local Administrators group. 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 groups policies. Although it is not necessary to copy the file to the servers \WINNT\INF directory, this is nonetheless where the default adm files are located.
Hey, I n
eed a little help here. I need to override Words blah, blah, blah

ADDITIONAL NOTE: For more information on Poledit.exe, see the Poledit.exes 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/). Theres 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

30

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

this: Can we do it? YES WE CAN! And, you dont 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 arent aware of the data contained on a computer, so dont feel bad if youre just hearing about this. Dont worry you wont be kicked out of the Geek club and marked for life with the word EndUser 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, theres 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 computers actual serial number! Can you even idealize how important that is?!! You only need to know a special connection stringthe 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)

31

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

winmgmt1 = "winmgmts:{impersonationLevel=impersonate}!//"& ComputerName &"" Once youve 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 cant . . . Giving the script a constant (SN) to work with for each SN in SNSet Displaying the computers 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 repositorys 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 BiosCharacteristics

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

32

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 elementoften this

will be a stock keeping unit (SKU) or a part number.


InstallDate When the object was installeda lack of a value does not indicate that the object is not installed. 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.MMMMMM(+)OOO. SerialNumber SMBIOSBIOSVersion SMBIOSMajorVersion Assigned serial number of the software element BIOS version as reported by SMBIOS Major SMBIOS version numberthis property is null if SMBIOS is not found. SMBIOSMinorVersion Minor SMBIOS version numberthis property is null if SMBIOS is not found. SMBIOSPresent Indicates whether the SMBIOS is available on this computer system Status Current status of the objectvarious operational and nonoperational 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

33

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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 Version Target operating system of the owning software element Version of the BIOSthis 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 programmers tool, but theres a huge amount of information included in the WMI SDK that is extremely useful to VB scripters. Youll be able to locate the WMI SDK download at the following Microsoft MSDN web page: http://msdn.microsoft.com/library/default.asp?url=/library/enus/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 computers BIOS must support a special industry standard called SMBIOS, and the version number must be compatible with 2.1 or better. For more information on SMBIOS, see the Desktop Management Task Force (DMTF) website: http://www.dmtf.org. If you are curious if your computers are SMBIOS compliant, check with the computer's manufacturer.

34

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

Q: Can I query information for other things like SQL Server?


Yes, you can! Sorry, that was another Bob the Builder reference. If youve 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 elsea 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 ADSI NameSpace LDAP Description This namespace implementation is compatible with Lightweight Directory Access Protocol (LDAP).

35

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. This namespace implementation is compatible with Novell NetWare Directory Service (NDS). This namespace implementation is compatible with Novell NetWare 3.x. 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 youre realizing that VB script is a mighty powerful tool.

Q: In VB scripts Ive 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 thats 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 programmers 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, its 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.

36

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 doesnt 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 youve 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, theres 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 = needed.

"Goodbye"

This

is

also

comment;

no

colon

is

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

37

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

possible. Youll thank yourself later. Sure, it takes a bit more time and feels like a pain, especially when youre 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 Ive 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 2433AC 2439AC Course Description Visual Basic Script and Windows Script Host Essentials Scripting Microsoft Instrumentation Windows Management

Table 5 Microsofts Office Curriculum for VB Scripting

You can find more information about these courses on Microsofts 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 nowMoulder 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 its just the systems administrator using VBScript to harass the enduser population. Moulder decides its 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 computers keyboard. You could write an

38

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

entire document with a VBScript and the SendKeys functionnot 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} 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, 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:

39

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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:

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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 youd 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 youre 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. 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/NTserv er/scriptit3.asp

2.

Q: Can I deliver software with VBScript?


Software delivery requires a mechanism. Thats not to say that VBScript cant 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

41

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

ntellimirror.asp). You can even utilize web pages and login scripts as a mechanism. Think of it in terms kitchen appliances. You have a toaster on one hand and a toaster oven on the other. Both can toast bread, but the toaster oven can do so much more. You can settle for a VBScript-only solution for delivering software, or you can utilize a full systems management application to deliver software, support users remotely, inventory the hardware and software of the companys equipment, control software licensing, etc. Particularly, from the software delivery aspect, a systems management application can offer some comprehensive features that manual solutions cant 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 applications 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 printers 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:"

42

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

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

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, and they always have been. Because of the way a printer installation interacts with the computer at the hardware level, its usually best to just use the vendors printer installation files. Thats not to say that VBScript cant be utilized to kick-off printer software installation, or another interesting feature of which you may not be aware.

44

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

Windows 2000 and later have a DLL that can be used to install printers with configuration options. PrintUI.dll contains the functions that post Windows 2000 computers use when installing printers, and you can access the functions with a single set of command line options. You can view all of the options available to you through the PrintUI.dll file by typing the following in the Start | Run dialog box: rundll32 printui.dll,PrintUIEntry /? When this command runs, the following dialog box is displayed, allowing you to review the options:

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.

45

JUST THE FAQS TO UNDERSTANDING VBSCRIPTING BASICS: PART I

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 cant 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 its doing and how its doing it, reusing the code, and finally, using the basics as a foundation. As more and more people wear down their soles on the Geek highway, your plight in life will become nothing more than their roadside scenery. As their speed picks up, you will meld into the blur of the rushing landscape. VB scripting is more than just a momentary fascination. It is a stepping-stone in the evolution of a new career, a new talent, or of advancement to a higher level. In the coming years, or even months, enterprise scripting will ultimately become a requirement for employment. Reading and remembering the basics outlined in this book gives you a solid foundation to construct a good working knowledge of scripting.

46

GETTING

STARTED

W I T H

VISUAL

BASIC

SCRIPTING

R E S O U R C E S
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

47

You might also like