Just the FAQs to VB Scripting Basics

Share Embed Donate


Short Description

Download Just the FAQs to VB Scripting Basics...

Description

Part I: Ge tting Sta r ted w ith Visua Visua l Ba Ba sic (VB (VB)) Sc r ip ting SUPER-GEEK,

STEP

I—OR,

GETTING

TO

THE

MOUNTAIN

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

M

uch of your life, you’ve felt just a little bit off-center. Your friends and co-workers have noticed it, too. Whether it was their issuances of “Geek-boy” in hushed tones, or their smattering of verbal applause when you solved something no one had been able to before, you’ve felt that there was something more for you in life – something only the gods could have ordained. Not only that, just when you thought you were getting much closer to being accepted in social circles (hmmm…or maybe it’s just that you are being tolerated because they now NEED you), Windows Script Host entered your life. You can’t quite put your finger on the feeling, but it’s as if destiny has arrived. Windows Script Host is the key you’ve been looking for. Like a burning ember on a mountain in view, fulfillment and redemption are just a hardened climb away. In this book, you’ll take the first steps toward that burning ember, by understanding what Windows Script Host really is and how to get help with the language, by learning what a powerful scripting language is before you and how you can get to the base of that mountain. This book centers on the most frequently asked questions (FAQs) that individuals pose when they are just embarking on their scripting journey. To date, the Internet has resources littered about that contain the best answers when starting out for the scripting prize. This book serves to centralize those great answers, so you can just “dig in” instead of searching the vast World Wide Web to try to pacify your curiosity.

Q: Wha t is Wind o w s Sc rip t Ho H o st? 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.” 

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT 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 Scrip t 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: Wha Wha t c a n I d o w ith WS 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.” 

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

For those too young or too cool to remember MacGyver, look at  this link: http://www.jumptheshark.com/m/macgyver.htm. As amazing as that show was (groan), WSH is very much the MacGyver of the Windows computing environment. A better question might be, “What can’t I do with WSH?” WSH is ideal for logon scripting, administrative scripting, and machine automation. You’ll understand further just how powerful WSH is as you read through the rest of the book, but here’s a small sample. With WSH you can:



Print messages to the screen



Retrieve and modify environment variables



Map network drives



Modify registry keys



Connect to printers



Write and read files



Retrieve computer inventory information

Q: Whic h ve rsion o f WSH d o I nee d ? Windows Script Host is an ingenious tool, comparable to other technologies. Take for example, your old DVD player. It plays the latest DVDs, but it’s too outdated to play MP3 CDs. Having that kind of functionality is a home theater pundit’s dream. So, after a short trip to the local electronics store and a quick cable changeover, the latest remix of the Elvis song, “Little Less Conversation,”  is slicing the living room with its funk beat. However, does the new DVD player still play your old DVD movies? You bet. If the DVD manufacturer stopped supporting the playing of older DVD disks, just to add MP3 capability, there would be serious backlash – and quite a few product returns. WSH may not be as cool as the big “E” (or it may be to some of you – God forbid), but it works much the same way as that new DVD player. Installing the latest and greatest version of WSH yields big benefits. Not only will your computers be able to utilize the latest functions of the updated engine, but the old functions will continue to work too. Plus, version 5.6 adds some extra neat, new features, as well as bolsters security. I cover this in the next section.

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.

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

Okay, to better answer which version of WSH you need, let’s just say it’s best to have the latest and greatest version. Why? Well, not only do subsequent versions address bug fixes, they also offer new features of which you can take advantage. In addition, you can still utilize the features you are already used to, because the current version is backward compatible – meaning you are not going to lose functionality at all. You are just adding new and exciting features to your ever-growing Geek Toolkit.

Q : Ho w d o I d e p l o y t h e l a t e st v e r si o n o f WSH? This is the age-old question, isn’t it? When a new patch or security update is released, it suddenly becomes critical that it is deployed throughout your company. If your company consists of 12 employees who share 5 computers, then you’re probably feeling pretty comfortable and getting the sleep requirements recommended by the Surgeon General. However, if you happen to work for a company with 70,000 employees in 80 countries, each with their own computer, your post-work life is most likely non-existent. You feel more like a 1st year Med student than someone who spent their early years worshipping bits and bytes, thinking what a cool job working with computers could be. Your alarm clock is your pager and each person in your company has beeped you awake more than once. There are numerous ways to deploy updates, particularly a new WSH version. Several come to mind, like Microsoft Systems Management Server (http://www.microsoft.com/smserver/default.asp), Altiris Deployment Solution (http://www.altiris.com/products/deploymentsol/), login scripts, batch files attached to emails, etc. Nevertheless, the scope of this book is not to delve too deeply into software deployment technologies. Instead, I only want to give you the information that allows you to use your favorite method of deploying the latest WSH version, successfully. The installation executable name for WSH is Scripten.exe, downloadable from Microsoft’s scripting website at: http://msdn.microsoft.com/downloads/ default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/728/ msdncompositedoc.xml&frame=true.

TIP: There are specific downloads for the different versions of Windows. For example, there is one download for Windows 2000 and others just for Windows NT, 98, and ME. Make sure you use the correct download for the target platform. Windows XP already has the most current version of WSH installed as part of the operating system load.

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

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

Figure 1 – Window s Script Host 5.6 Installation Options

Per Figure 1, running the installation with the /Q switch will cause WSH 5.6 to install quietly. Installing the WSH upgrade, even with the /Q switch, will require the computer to reboot to finish the installation on the next boot. Remember when I said vendors now include all hidden switch functions in the /? command? Well, there are still some exceptions to the rule. If it is your task to deploy the WSH upgrade to a multitude of computers during the workday, the end-user will probably get upset if they have to close all of their applications and reboot the computer. Even though the installation Help screen in Figure 1 doesn’t show a command-line option to tell the installation not to prompt to reboot when finished, there is a command option to accomplish this. Running the following command-line will cause WSH to install silently and to suppress any reboot message: scr56en.exe / q:a / r:n Note that this command does not mean that the computer doesn’t still need to be rebooted at some point. In fact, for the installation to finish completely, the computer will need to be restarted, and you can notify the end-users to do this at their leisure. The WSH upgrade attempts to overwrite files during the installation process. If some of these files are in-use during the install (and they will be), they are flagged to be replaced during the computer boot process. In effect, the new version of WSH will not work until the computer’s memory is flushed through a reboot. Then, why aren’t these additional switches readily available in the installation Help screen? That’s a very good question—one that I myself will ask when I can pinpoint the correct person. Until then, the following table (Table 1)

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

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

/q

Quiet mode—skips all user prompts

/q:u

User quite mode—shows some dialog boxes

/q:a

Admin quite mode—does not show any dialog boxes

/r:n

Never restart—do not restart the computer even if it is necessary to complete the installation

/r:i

Restart if necessary—automatically restart the computer if it is necessary to complete the installation

/r:a

Always restart—always restart the computer after the installation

/r:s

Silent restart—automatically restart the computer without prompting the user 

/s

Silent mode—some programs use this switch instead of the /q switch to install in quiet mode

/n:v

No version checking—installs the program over any previous version

Table 1: Alternate Installation Switches

Q: Which features does WSH 5.6 offer me? Now you are thoroughly interested in WSH version 5.6. Your interest has been piqued and you know that storing extra information in that brain of yours will make you a star at the next Geek Games. WSH 5.6 is quite a leap from earlier versions. Of course, Microsoft included bug fixes. A service level can’t be upgraded without addressing current problems. There are quite a few people in the IT industry who would whine for weeks if a specific bug wasn’t addressed. For a list of the bug fixes, read through the Windows Script Host 5.6 documentation at: http://msdn.microsoft.com/ downloads/default.asp?url=/downloads/sample.asp?url=/msdnfiles/027/001/728/msdncompositedoc.xml&frame=true.

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

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

Security If you read the trade-rags very often, you can’t turn too many pages without a security article jumping out at you. Security is THE hottest topic in the IT industry at the present—and rightly so. .VBS and .VBE files have had their day in the sun as potentially dangerous email parasites. Without special caution, they could rear their ugly heads once again. When you think about it, anyone who can become even remotely adept at writing VB scripts could be considered a dangerous person. The VB scripting language is so powerful that there’s very little you can’t do with it. What a person does with the power is up to them. Some turn to “the dark side” and write scripts that can damage data. Whether it starts as a practical joke or just a dreadfully devious person bent on the destruction of mankind, using VB scripting knowledge for anything but good is, well . . . just bad. With the release of WSH 5.6, Microsoft included some critical configuration parameters in the form of registry key values. By modifying these registry values, you can beef up security for the scripting engines installed on your company computers. Browse through Table 2 below for full understanding of  your configuration options. Each of these registry values can be found in both HKLM\ Softw are\ Microsoft\ Window s Script Host\ Settings and HKCU\ Software\ Microsoft\ Window s Script Host\ Settings.

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

Enabled

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

Remote

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

TrustPolicy

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

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

scripts will display a prompt, warning the user that they are about to do something dangerous and giving them a chance to back out. If 2, then only trusted, signed scripts will be allowed to run. On WinXP, you also have the option of using the SRPs—see UseWINSAFER below. Default is 0 if not present. 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 – W SH 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.

A r g u m e n t Ha n d l i n g 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.

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

Ru n n i n g Sc r i p t s Re m o t e l y 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.

Pr o c e s se s a s O b j e c t s You determine the status of spawned processes and access their standard I/O streams.

Se t t h e C u r re n t A c t i v e D i re c t o r y You can determine/modify the active process’s current working directory.

Q: What’s the d ifferenc e between WSc ript.exe and CSc ript.exe? Friday night is the big shindig where you may receive an award for your excellent service this year. You worked through three colds and one bout of  laryngitis and made it through the entire year without missing one in-service day of work. It’s a black-tie affair, and your wife is expected to attend with you as your Plus One. Frankly, due to your unflinching dedication, you’ve summarily forgotten this year to take your wife to a movie or even a simple dinner. So, this night out seems to her the best chance to live-it-up, be seen, and set the mode in style. She’s so excited that she’s been out every day to several different shopping centers, looking for just the right thing to wear. With so much on the line, which car do you take to the company ceremony? Do you take the beat-up Chrysler that you drive to and from work every day—the same one that has McDonald’s coffee stains in the passenger seat—or do you take the “good” car, the one you let your wife drive? If you have to think about that too long, you may need to take a few days of   “sick” time the following year. Just like there’s a car for every occasion or an outfit that goes best with an event, WSH has two specific scripting engines that are used for appropriate instances. You can run WSH either from the protected-mode Windows-based host (Wscript.exe) or from the real-mode command-shell-based host (Cscript.exe). The difference between the command-line and the Windows-based engines is only in the output — WScript.exe generates windowed output, while CScript.exe sends its output to the command window in which you started it. The only real way to understand this difference is to see a script in action.

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

Let’s take a look at a simple script. This script, written for CScript.exe, prompts you for a specific computer name in a nice Windows box, as shown in Figure 2. It then connects to the computer you specified, retrieves service information, and then displays the output in a DOS window, as shown in Figure 3.

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

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

Se r v i c e I n f o r m a t i o n f o r C Sc r i p t . v b s ComComputerName = InputBox(“Enter the name of the computer you wish to query”) winmgmt1 = “winmgmts:{impersonationLevel=impersonate}!//”& ComputerName &”” Set SPSet = GetObject( winmgmt1 ).InstancesOf (“Win32_Service”)   WScript.Echo “==========================================”  WScript.Echo “Service Information for “ & “”& ComputerName &””   WScript.Echo “==========================================” For each SP in SPSet  WScript.Echo “Service Name: “ & SP.Name  WScript.Echo “Location: “ & SP.PathName  WScript.Echo “PID: “ & SP.ProcessID  WScript.Echo “Type of Service: “ & SP.ServiceType  WScript.Echo “Service State: “ & SP.State   WScript.Echo “==========================================”   WScript.Echo “==========================================” next

When you look again at the information shown in Figure 2, you can see a long list of information. This output is actually a multitude of pages long, which causes the display in the DOS window to scroll for almost 30 seconds. If you happened to run this script with WScript.exe, a window would display for EACH line you see in the figure. In addition, since the output is an enormous amount of information, you would see a new window pop up for EVERY new line, such as the window shown in Figure 4. If you calculate the number of services that can be installed on any given computer, multiplied by the number of output lines for each service as defined in the script, that’s almost 800 windows popping up in your face every one to two seconds. The worst part . . . you have to hit the OK button on each Window before the script will advance.

Figure 4 – Crazy WSH Window Meant for CScript.exe

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

Unless you’re a psychotic person or someone with a lot of time to spare, you will agree that this is time consuming and needless. If you somehow get duped into running a script with WScript.exe that was meant to be run with CScript.exe, there’s an easy way to break out of the seemingly endless loop. Both engines run as Windows processes. Shown in Figure 5, executing Windows Task Manager and choosing the Processes tab, you only need to search the list for the running engine, highlight it, and click the End Process button to exit your worst scripting nightmare.

Figure 5 – Wscript.exe Running as a Window s 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:

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

Se r v i c e I n f o r m a t i o n f o r WSc r i p t . v b s: 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 I nformation Output Designed fo r W Script.exe

You’d probably even want to go a bit further, because you would still expect to see one window for every installed service. While this minimizes your headache somewhat, it doesn’t cure it. The best method is to pipe the output to a text file, so you can review the contents at your leisure, either on-screen or printed on a piece of paper.

When WSH is installed, WScript.exe is designated as the default scripting engine. Then, anytime a VB script or Java script is executed, WScript.exe jumps to attention and hosts the script for you. If you code the majority of your scripts CScript.exe to host, you may want to change the default. You can do this by running the following command-line: cscript//h:cscript Don’t worry, this doesn’t have to be a permanent change! Once you change it, you’re not stuck with it for your entire scripting life. Like Superman in the

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT 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:w script Ah . . . so then, there are command-line options for the scripting engines? No, I’m not holding out on you. There are more command-line options for both CScript.exe and WScript.exe. I cover those in the next section.

Q: What command-line scripting engines offer?

options

do

the

In the early days of computing, a horde of commands hid spectacular options. These options came in the form of command-line options and arguments, much like the option in the previous section to change the default scripting engine. Somewhere along the line, someone got smart and started incorporating these options and arguments into a neat, new argument all its own. This argument came to be called the /? (slash-question mark), and sometimes the /help (slash-help). Very cool—what was once fodder for a secret society of programmers is now at your disposal to do with what you will. WSH is no exception. Both WScript.exe and CScript.exe have command-line options and arguments available. You can access them the normal way, by typing in the engine with the /? (WScript.exe /? or CScript.exe /?). Instead of  writing out the switches for each engine, it’s best to go right to the source. Figure 6 shows the command-line options for WScript.exe, and Figure 7 displays CScript.exe’s options.

Figure 7 – W script.exe Command-Line Options

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

Figure 8 – Cscript.exe Command-Line Options

You’ll notice, by looking between Figures 5 and 6, that there is only one difference in the command-line options: the  / / U switch used with CScript.exe.

Q: What are the differences between VBScript and JavaScript? When you’re just starting out, heading down that scripting path, you come across your first conundrum: two scripting languages. Which one you use really depends on what your needs are but also what your tastes are like. Some people choose Coke; some choose Pepsi. Unfortunately, the scripting languages don’t have someone like Britney Spears to lead you in one direction or the other. There is no song and dance routine to help you decide which language is best for you. If there was, I suspect more people would be interested in scripting. JavaScript is a scripting language targeted toward web development. If you’re working directly with web technologies, JavaScript should be your tool of  choice. Sun Microsystems (http://www.sun.com/) derived the name JavaScript from the original Java language they developed. VBScript is used, primarily, in companies that want to manage their computing and networking environment. From inventorying computer hardware, to changing network passwords, to deploying software, VBScript is a powerhouse for the enterprise. The name VBScript is taken from Microsoft’s (http://www.microsoft.com) own Visual Basic programming language.

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

We have written this book for those individuals who want to add scripting to their IT tool belt, to be used as a way to increase their skill-set and  to provide more value for their company and employment. Since, we won’t be discussing web development, the scripts and script discussions in this book will be targeted at the VBScript language. Both scripting languages are very similar to the counter-parts after which they are named. There’s very little difference between the full-blown programming language and the light-weight scripting language. “VB Jr.” and “Java Jr.” have many of the same functions that their Big Brothers have available. The major difference is that scripting languages cannot be compiled and run as standalone applications – meaning you still need WSH installed to host the script. An application written using a full programming language doesn’t need a host; it can run on its own on the computer and operating system it was written for. However, you can “encode” a script. See the next FAQ for details.

Q: How c an I protec t my sc ripts? As outlined in the previous FAQ, you can compile code written with development languages, but you can’t compile script language code. Compiling code for a programming language also keeps unwanted eyes from viewing and modifying the code that a programmer worked hard to create. You can do something similar with scripts too. We call this “encoding.” A “script encoder” is a simple command-line tool that enables script developers to encode the final script so that it cannot be viewed nor the source modified. Microsoft has a script encoder available for download at the following location: http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.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, didn’t I? Well, if it’s so powerful, why can’t it encode itself ? It can. I hate to throw a lot of code at you in a book on VBScript basics without spending time explaining it, but you can always come back and play with the code later on, once you’ve become more comfortable with the scripting languages. The following will encode any script written with VBScript or JavaScript. All you have to do is have this script sitting somewhere in the file system, and then drag and drop the script you’ve created onto it. Your script is encoded automatically!

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

En c o d e . v b s 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,

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

bstrStreamIn,

0,

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT 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: What’s the b est wa y to lea rn to sc ript? This question comes up quite a bit on web forums and email discussion lists. When an individual finally decides that “today is the day” to start on the path to scripting, he turns to those he feels would know best where to begin. If you notice, every one to whom he asks this question will give a slightly different answer. Some will give a long list of scripting books; others will copy and paste links to their favorite scripting websites. Despite the laundry list, one point rings through every time: you learn by doing. Stop and remember . . . way back . . . ok, even further than that . . . when you started learning how to drive a car. You probably gave your parents quite a few heart attacks, but they knew the only way you were going to get the driving thing down was to sit behind the wheel and work out your own rhythm. Your dad gave you the basics: “You sit behind the steering wheel. The brake pedal is on your left, and the gas pedal is on your right. That’s the turn signal. No, no, on the other side—those are the wiper blades.”  Better than learning to drive, you won’t have to worry about needing a licensed scripter sitting in the passenger seat. You’re on your own, doing your own thing, learning at your own pace, and getting your own rhythm. What’s more, unless you write a script that reboots the file servers and test it in a production environment, you won’t cause too many heart attacks. There is no licensing fee for a script. As you are surfing the web, finding scripting websites and reviewing script code, grab it all and save it somewhere on your hard drive. Be as script-hungry as you like, and no one will care. There are quite a large number of resources available to help you learn scripting. Grabbing scripts from these resources and rolling up your sleeves and just digging in is the main key to understanding the languages. One of the most exciting aspects of the scripting community is each individual’s

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

willingness to share what they’ve done. A couple quick changes here, an addition of a line or two, and a script you found or received from someone is ready to work in your environment. Remember, though, someday other people will be just like you – chomping at the bit to learn how to script. Don’t be stingy and keep your scripts locked up in a box somewhere. By sharing the solutions you have scripted, you not only help the “newbies” get up to speed, but you help keep a community growing and going strong. Whether you believe it or not, your best and most loyal companion on your scripting journey is the actual scripting documentation provided by Microsoft.  “What?” you say, “You mean the same company that spearheaded the effort to rid the world of product manuals?” Yep, the exact same. I use the documentation regularly. It not only contains comprehensive information, but also includes script examples in both VBScript and JavaScript that you can copy and work with yourself. A quick jaunt over to Microsoft’s scripting website (http://msdn.microsoft.com/scripting) gives you the download links for all of  the documentation. Here’s a list of what’s available:







Script Debugger Documentation—http://msdn.microsoft.com/ library/enus/sdbug/Html/sdbug_1.asp Remote Scripting Documentation—http://msdn.microsoft.com/ library/enus/rmscpt/Html/rmscpt.asp JScript Documentation—http://msdn.microsoft.com/library/ en-us/script56/html/js56jsoriJScript.asp











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

en-

Windows Script Host Documentation—http://msdn.microsoft.com/ library/en-us/script56/html/wsoriWindowsScriptHost.asp Windows Script Components Documentation— http://msdn.microsoft.com/library/en-us/script56/html/lettitle.asp Microsoft Windows Script 5.6 Documentation — http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.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 you’ve had your fill of Microsoft’s documentation, then what? The Internet is such an enormous place. Surely there are some websites I can give you to go on your scripting shopping spree. Well, here they are:



MyITforum.com —http://www.myITforum.com

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT 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. There’s also a dedicated VB scripting web forum where people post problems and others post answers, complete with script examples. Before you click away from the site, make sure to check out the VB scripting downloads area. Not only can you seize some free script downloads, but as a site member you can post your own solutions. The majority of the online scripting community runs through this site. 

Microsoft’s TechNet Script Center —http://www.microsoft.com/ technet/treeview/default.asp?url=/technet/scriptcenter/default.asp Recently inaugurated, this site is quickly becoming the epicenter for script downloads. This repository of scripts continues to grow. There has been no formal communication as to a schedule when new scripts are released, so you’ll need to check back periodically.



WSHScripting.com—http://www.wshscripting.com/ Another hit-and-run site for grabbing scripts, WSHScripting.com offers a nice library of downloadable script solutions.



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

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

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

anything is. It is now more likely that a wasp will sting you, than a Windows script will “infect” your computer. With all of the tools available to minimize your vulnerabilities, you are as safe as you want to be. These days, if a virus infects your machine, it’s probably your own fault. Inserting old diskettes into your disk drive, reading your email archives that date back to the dawn of the Internet, or not applying the latest Anti-virus patches—you can only blame yourself. You can even further minimize your vulnerability to running unsafe or untrustworthy Windows scripts by making a simple change to the Windows registry. Associate all Windows scripts with Notepad, so that when a script is double-clicked or executed, it opens in the text editor, instead of running as a script. You can still run the script as a script by initiating the execution of the script, using the appropriate WSH engine. For example, instead of just running encode.vbs from a command-line, run CScript.exe encode.vbs. This is a manual way of telling WSH that it needs to do something. Windows scripts are no longer “allowed” to run unassisted. You have to tell WSH which script engine to use. This will save you some sleepless nights worrying that an end-user may be poking around in his computer files and double-clicking on a script to remove access to the entire computer. The registry modification:

Hive : HKEY_Cl a sse s_Ro o t 1.

Key = JSEFile\Shell o 

2.

New Value = Edit

6.

New Value = Edit

Key = VBEFile\Shell

New Value = Edit

Key = WSHFile\Shell o 

7.

New Value = Edit

Key = WSFFile\Shell o 

Key = VBSFile\Shell o 

4.

5.

Key = JSFile\Shell o 

3.

New Value = Edit



New Value = Edit

Key = WSHFile\Shell\Edit\command o 

New Value = C:\WINNT\System32\Notepad.exe %1

You’ll notice that the location to Notepad.exe is listed as C:\WINNT\System32, which is the directory fro Windows NT, Windows 2000, and Windows XP. You’ll need to modify that value if you want to  protect Windows 95, Windows 98, and Windows ME computers. Notepad.exe is normally stored in the C:\Windows directory on these computers, but you had better check to make sure.

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

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

Notepad To open or edit a script in Notepad, you only need to right-click on the script, and choose Edit. By performing this action, I opened the Encode.vbs script pasted earlier in the chapter, shown in Figure 9.

Figure 9: Encode.vbs Opened in Notepad

Notepad is the best tool to start with, and it helps reorganize your mind to be more in tune with the styles and formatting associated with VB scripting. After a few weeks of coding, you’ll start dreaming in all black-and-white text. Notepad has some of the same features you’ll find in other script editing tools. You can Edit | Find specific text, and replace it with your own text. You can

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

also skip to a specific line number. This extremely important feature needs to be present in any script editor to which you eventually switch. Why? When you start coding you’ll understand better, but when your code is not quite right, and you attempt to run your script, an error message will display, giving you the line number where the error occurred (similar to the error message shown in Figure 10).

Figure 10: Script Error at Line 2 Character 1

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

1.

With Word Wrap turned off (the Go to Line command will not work when Word Wrap is enabled. You disable it by un-checking Word Wrap under Notepad’s Format menu.), hit Ctrl-G on your keyboard. You’ll be presented with the pop-up screen shown in Figure 11.

Figure 11: Go to Line Command in Notepad

2.

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

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

I really couldn’t live without this great feature, and you’ll quickly find you feel the same. I can’t think of a single script I’ve written where I didn’t have to   “tweak” it a bit before it would work properly, and having the Go to Line command available is a time-saver.

ConTEXT I couldn’t finish off this FAQ without giving you at least a couple alternatives to Notepad. I search periodically to see if anyone has developed a new tool for creating and editing VB scripts. On one of my searches, I found ConTEXT (http://www.fixedsys.com/context/). ConTEXT is a general-purpose programmer’s editor, allowing you to work with more than just VB scripts. Shown in Figure 12, ConTEXT is a nice editing tool with a great interface.

Figure 12: The ConTEXT Pr ogrammer’s Editor

ConTEXT not only colorizes the functions of your code for easy recognition and includes the adored Go to Line function, but it also has a very handy Macro feature, giving you the ability to record repetitive tasks. Instead of hand typing a section of code you use often, you can record it once and only need to choose to use it later on. Neat!

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

ConTEXT is a freeware application. All it will cost you is a little bandwidth for downloading the 1.03 MB file. I guess you could say it costs just a tad bit more than Notepad. When you’re ready to move on to another scripting or programming language, ConTEXT fits the bill, as there are “highlighter” 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



DCL Language



AnSys Macros



DOS Batch



AutoIt



Euphoria



AutoLisp



HP48



AWK





Clipper



Cobol



ConTEXT Highlighter Files

JCL (Job Control Language)



PowerPC GNU Assembler



SciLab



SkdTXT



SNMP MIB



SWI Prolog



KiXtart



VHDL



Latex



Visual IRC v2.0



Liberty BASIC





CSharp



MIPS Assembler



CSS



PCBus



Windows resource scripts x51 Assembler

WM I Sc r ip t o m a t i c One last recent entry to the school of automated utilities is the WMI Scriptomatic utility. I couldn’t finish this FAQ without making mention of this great script. Yes, you heard me correctly. This utility is in fact, another great script, which you can modify to meet your needs. In fact, someone recently modified the WMI Scriptomatic script to connect to a Microsoft Systems Management Server and retrieve information from there. You can find and download this modified script, by going to the myITforum.com search engine (http://www.myitforum.com/search.asp) and searching for the keyword scriptomatic. The WMI Scriptomatic is an example of a hypertext application, essentially a Web page that uses a .hta file extension. When executed, this script connects to the local computer’s WMI repository (a database full of information about the computer) and then presents you with all of the values it finds. Choosing a value, the WMI Scriptomatic utility will automatically generate the VB script you need to use to pull the information from the WMI repository yourself. How’s that for writing your first scripts? Figure 13 shows the WMI Scriptomatic utility being used to build a script to pull information about the computer’s serial port hardware. From the interface, you

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

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

Figure 13: WM I Scriptomatic Utility Creating Script for Serial Port I nformation

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

Q: How c an I ma ke others run my sc ripts? 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?

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

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



In a login script



From a web page



From a network share



With a remote execution utility



By utilizing Remote WSH



Copied to the remote computer and executed there

Lo g i n Sc r i p t s Any company that has a network managed through a domain potentially utilizes login scripts. Login scripts allow network administrators to send instructions to the remote computer each time it logs onto the network. VB scripts work great when inserted into login scripts and make an excellent solution for making sure the scripts run on every computer in the organization. Some companies have even replaced their login scripts completely with VB scripts! OK, that’s just crazy, you say. Granted, some extreme knowledge of  VB scripting is required, but it can be done and easily. If you remember how powerful VB script is, it may make better sense, realizing that if you have replaced your login scripts with VB scripts, you can utilize that power anytime you want, instead of searching the Internet for a freeware tool that will work in your environment.

Ex a m p l e o f V BSc r i p t I n se r t e d i n t o Lo g i n Sc r i p t The following bit of VB script code provides an example of something you might want to place into your login scripts. This “codelet” simply maps the network drives O and Q for the computer logging into the network. With just a few lines of code, you can provide these network drive mappings. Dim net Set net = CreateObject("WScript.Network") net.MapNetworkDrive "O:", "\\server\share" net.MapNetworkDrive "Q:", "\\server\share"

Network Share VB script works like any other application or program that executes on a local computer, so it’s not surprising that you can place a VB script on a network share that users have access to and have them run the script in some way. Just plop the script on the network, and offer a link to run the script. You can offer the link through an email, a login script, or some other method you

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT 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.

Ru n o n Re m o t e C o m p u t e r 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.

We b Pa g e More and more companies utilize some kind of internal website for offering company information. Some go even farther by providing software downloads and installations. Websites are a great tool for company communications. VB scripts run great from web pages—either through a link that executes the script, or a component that runs the script when a specific web page is loaded into the computer’s web browser.

Remote Execution 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 you’ve watched many horror movies with a mad dictator or scientist, this is where you would hear an evil laugh emanate—Bwahahahaha . .. One of the more popular tools in this area is from SysInternals. SysInternals offers a slew of freeware utilities geared toward aiding the systems administrator. PsExec is the utility that allows remote execution of commands/programs. It doesn’t need to be installed on the remote computer, just run from yours, so there’s no overhead on the remote computer. PsExec utilizes the following command line options: usage: psexec \ \ computer [-u username [-p passwo rd]] [-s] [-i] [-c [-f]] [-d] program [arguments]

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

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

to enter a hidden password . 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. Copy the specified program to the remote system, even if the file already exists on the remote system. Don't wait for application to terminate. Only use this option for non-interactive  applications. Name of the program to execute Arguments to pass—note that file paths must be absolute paths on the target  system .

You can download PsExec from the following location on SysInternals’ website: http://www.sysinternals.com/ntw2k/freeware/psexec.shtml.

Remote WSH With the remote execution utilities on the market, you didn’t think Microsoft would sit idly back and not supply this functionality in WSH, did you? Not likely. If it’s a good, sound technology you can expect Microsoft to incorporate it eventually. Remote WSH is a new technology included in WSH 5.6. It provides the ability to run a script on a remote machine or machines. With Remote WSH, the script is physically copied from the local machine to the remote machine before executing. In order to enable Remote WSH functionality, you must first set up the remote machine with the proper security settings.

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

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

Se ttin g - Up Re m o te 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.

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

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

3.

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

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

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

For more information on Poledit.exe, see the Poledit.exe’s online help system. Poledit.exe can be run from the command. 4.

WSH should now be enabled on the machine.

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

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

this: “Can we do it? YES WE CAN!” And, you don’t need to set up Remote WSH to do it. Much like an application can query a SQL database for data, you can utilize VB scripts to connect to a remote computer and pull information about that computer. Each computer stores a significant amount of data about itself. This data is stored in the WMI repository. The WMI repository works similarly to an SQL database, except the WMI repository is filled with data automatically. There are lots of administrators who aren’t aware of the data contained on a computer, so don’t feel bad if you’re just hearing about this. Don’t worry – you won’t be kicked out of the Geek club and marked for life with the word “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, there’s a Computer class (Win32_ComputerSystem) which stores information (Properties) about the local computer, such as the Current Time Zone, the Manufacturer of the computer, and the Domain that the computer belongs to. Believe it or not, you can also query this database for the computer’s actual serial number! Can you even idealize how important that is?!! You only need to know a special connection string—the Geek-to-Computer handshake. The following “handshake” connects to the computer BIOS class on a remote computer, allowing you to get information about the installed BIOS options (which, incidentally, contains the serial number of the computer). To make it simple, the script first prompts you for the name of the computer from which you want to extract the serial number.

Figure 14: Dialog Box Requesting Remote Computer to Connect to

‘Dialog Box Setup: ComputerName = InputBox("Enter the name of the computer you wish to query") ‘Connection string (handshake)

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

CurrentLanguage

Name of the current BIOS language

Description

Description of the object

IdentificationCode

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

InstallDate

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

ListOfLanguages

List of names of available BIOS-installable languages

Manufacturer

Manufacturer of this software element

Name

Name used to identify this software element

PrimaryBIOS

Indicates whether this is the primary BIOS of the computer  system

ReleaseDate

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

SerialNumber

Assigned serial number of the software element

SMBIOSBIOSVersion

BIOS version as reported by SMBIOS

SMBIOSMajorVersion

Major SMBIOS version number—this property is

if 

SMBIOS is not found. SMBIOSMinorVersion

Minor SMBIOS version number—this property is

if 

SMBIOS is not found. SMBIOSPresent

Indicates whether the SMBIOS is available on this computer  system

Status

Current status of the object—various operational and 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

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT 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

Target operating system of the owning software element

Version

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

Table 3 – Sampling of WM I Repository BI OS Class Properties

The best resource of information about the WMI repository is included in the Help files of the WMI Software Development Kit (SDK). I realize this sounds like a programmer’s tool, but there’s a huge amount of information included in the WMI SDK that is extremely useful to VB scripters. You’ll be able to locate the WMI SDK download at the following Microsoft MSDN web page: http://msdn.microsoft.com/library/default.asp?url=/library/enus/wmisdk/wmi/ wmi_start_page.asp.

For certain functions (like obtaining serial numbers), certain computer  requirements must be met. A specific version of WMI is required on each computer from which you want to retrieve the serial number. WMI 1.5 or better  is the requirement. Your computer’s BIOS must support a special industry standard called SMBIOS, and the version number must be compatible with 2.1 or better. For more information on SMBIOS, see the Desktop Management Task Force (DMTF) website: http://www.dmtf.org. If you are curious if your  computers are SMBIOS compliant, check with the computer's manufacturer.

GE T T I N G

S T A R T E D

W I T H

V I S U A L

B A S I C

S C R I P T I N G

Q: Can I query information for other things— like SQL Server?   “Yes, you can!” Sorry, that was another Bob the Builder reference. If you’ve taken the time to visit the website, the song is probably stuck in your head, too. To make it easier to access specific Microsoft server offerings, and to give better abilities to developers, Microsoft developed common “connectoids” called providers for many of their servers. Then, each provider includes a namespace or a number of namespaces. An example is the ADSI Service Provider, which includes several namespaces (shown in the table in this section.) As an example, the following utilizes the same type of handshake to connect to an Internet Information Services (IIS) server (notice the item in bold): Set IIsComputer = GetObject(" IIS://" & TargetComputer)

The following will connect you to a Microsoft SQL Server: Set objWbemSvc = GetObject(" Winmgmts://./root/MicrosoftSqlServer ")

You can actually get a list of the providers available on a given system with— what else—a VB script. Run the following on any computer to retrieve the list of available providers: Set objProvider = GetObject("ADs:") For Each Provider In objProvider  WScript.Echo Provider.Name  Next

Some common providers and namespaces:

Provider

NameSpace

Description

ADSI

LDAP

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

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

possible. You’ll thank yourself later. Sure, it takes a bit more time and feels like a pain, especially when you’re working feverishly on a new code solution, but the benefits definitely outweigh the time you lose initially.

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

Course Number

Course Description

2433AC

Visual Basic Script and Windows® Script Host Essentials

2439AC

Scripting Microsoft® 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.microsoft.com/traincert/default.asp.

Q: Can I use VBScript to send keystrokes to Windows? The SendKeys function of VBScript would have made for an interesting X-Files episode. I can see it now…Moulder and Scully are called to a local company to investigate strange writings on computers – all done without any user input. Scully tries to convince Moulder that there has to be a scientific reason behind it. Maybe it’s just the systems administrator using VBScript to harass the enduser population. Moulder decides it’s the work of technology obtained through the Roswell crash of 1947. He goes on to prove that the systems administrator is actually the only survivor of the Roswell saucer crash. The SendKeys function of VBScript probably one of the most popular functions. You can actually send keystrokes to the Windows shell, allowing you to automatically click through dialog boxes, or input text. You can also send any letter or number available on the computer’s keyboard. You could write an

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

Direct:

DoCompleteFirst:

DriverName:

EnableBIDI:

EnableDevQueryPrint:

ErrorCleared:

ErrorDescription:

ErrorInformation:

ExtendedDetectedErrorSt ate:

ExtendedPrinterStatus:

Hidden:

HorizontalResolution:

InstallDate:

JobCountSinceLastReset:

KeepPrintedJobs:

LanguagesSupported:

LastErrorCode:

Local: True

Location:

MarkingTechnology:

MaxCopies:

MaxNumberUp:

MaxSizeSupported:

MimeTypesSupported:

Name:

NaturalLanguagesSupported:

Network:

PaperTypesAvailable:

Parameters:

PNPDeviceID:

PortName:

PowerManagementCapabilitie

PowerManagementSuppo

s:

rted:

PrinterState:

PrinterStatus:

PrintJobDataType:

PrintProcessor:

Priority:

Published:

Queued:

RawOnly:

SeparatorFile:

ServerName:

Shared: False

ShareName:

SpoolEnabled:

StartTime:

Status:

StatusInfo:

SystemCreationClassName:

SystemName:

TimeOfLastReset:

UntilTime:

VerticalResolution:

WorkOffline: Table 6 – Printer Pro perties Available in the WMI R epository

I n st a l l i n g Pr i n t e r s Printer installations are a pesky prospect, and they always have been. Because of the way a printer installation interacts with the computer at the hardware level, it’s usually best to just use the vendor’s printer installation files. That’s not to say that VBScript can’t be utilized to kick-off printer software installation, or another interesting feature of which you may not be aware.

You're Reading a Preview Unlock full access with a free trial.

Download With Free Trial

J UST THE F A QS TO U NDERSTANDING V B SC R I P T I N G B ASICS: P A RT I

Figure 18 – Prompting for Network P ath and Printer

Then, it runs the proper PrintUI.dll switches to install the printer. Dim p  p = InputBox("Enter the network path to the printer you want to install:", "Add Printer", "\\Server\PrinterName") If p "" Then Dim cmd cmd = "rundll32 printui,PrintUIEntry /in /n" & p   WScript.CreateObject("WScript.Shell").Run cmd End If

Summary Someone once said that your journey begins with your first step. What a profound statement. By picking up this book and perusing through it, your   journey has already started. You can’t turn back now. If you do, you will be stuck at the base of the mountain forever. True enlightenment can be obtained by treading onward, picking up pieces here-and-there, downloading code and figuring out what it’s doing and how it’s doing it, reusing the code, and finally, using the basics as a foundation. As more and more people wear down their soles on the Geek highway, your plight in life will become nothing more than their roadside scenery. As their speed picks up, you will meld into the blur of  the rushing landscape. VB scripting is more than just a momentary fascination. It is a stepping-stone in the evolution of a new career, a new talent, or of advancement to a higher level. In the coming years, or even months, enterprise scripting will ultimately become a requirement for employment. Reading and remembering the basics outlined in this book gives you a solid foundation to construct a good working knowledge of scripting.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF