Flylib.com

Books Software

 
 
 

Microsoft WSH and VBScript Programming for the Absolute Beginner - page 18


Summary

This chapter has covered a lot of ground for an introductory chapter. Not only did you create your first VBScript, but you also learned how to use the WSH to execute it and to incorporate WSH elements within your scripts. In addition, you learned a lot about VBScript and how it relates to other languages that make up the Visual Basic family of programming languages. Finally, you created your first computer game, learning how to collect and validate user input and to display output. All in all, I'd say that this has been a very good start.



Challenges

  1. The Knock Knock game is a very simple game. Its main purpose was to introduce you to the basics of script and game development. Try to improve the game by adding additional jokes so that the game does not end after the first joke.

  2. Try running the Knock Knock game using both the CScript and WScript WSH execution hosts . How does the execution of the script change and why?

  3. See if you can create a new script that prompts you for your name and then displays a personalized greeting message that includes your name. Hint: When displaying the customized greeting message, you will need to concatenate (glue together) the name of the user with a greeting message as follows :

    MsgBox "Greetings "& UserName
    



Chapter 2: Overview of the Windows Script Host

Overview

Because VBScripts cannot execute without an execution host of some type, the WSH is at the heart of any VBScript that you run from the Windows desktop or command line. The WSH not only provides an environment in which VBScripts can execute, but it also provides scripts with direct access to Windows resources such as the Windows desktop, Start Menu, registry, event logs, and network resources. In order to effectively create and execute VBScripts in this environment it is essential to have a good understanding of the WSH core object model. This includes knowing about the methods and properties associated with WSH objects, as well as how to configure the WSH to best suit your needs. In this chapter you will learn

  • About the objects that make up the WSH core object model

  • How to use WSH object methods within your VBScripts

  • How to use WSH object properties within your VBScripts

  • How to configure the execution of the WScript and CScript execution hosts



Project Preview: The Rock, Paper, and Scissors Game

In this chapter you will learn how to create a computer version of the Rock, Paper, and Scissors game that you used to play as a child. The game will begin by displaying its rules and then it will ask the player to choose between one of the three possible choices. Once the player makes his or her selection, the game will randomly make its own selection and display the results. Figures 2.1 through 2.3 demonstrate the flow of the game.

click to expand
Figure 2.1: The script begins by displaying the rules of the game.

click to expand
Figure 2.2: The player then types in his or her selection.


Figure 2.3: Then the script randomly picks a selection and displays the results of the game.

Through the development of this game you'll get a chance to practice incorporating WSH objects and their methods into VBScripts. You'll also learn how to perform a little simple conditional logic, as well as take a peek at using a number of built-in VBScript functions.



A Detailed Examination of WSH Components

Think of a computer, its operating system, and its hardware and software as being a collection of objects such as files, disk drives , printers and so on. To automate tasks on Windows operating systems, VBScript needs a way of interacting with these objects. This is provided by the WSH's core object model.

An understanding of the WSH core object model is essential to your success as a VBScript programmer. Not only will it provide you with the technical insights you'll need to development scripts that will run on Windows operating systems, but, by introducing you to working with objects, it will also prepare you to work with other object models. For example, many Windows applications, including Microsoft Office applications, expose their own object models, allowing VBScript to programmatically manipulate them. In addition, other VBScript execution hosts , such as Internet Explorer, provide VBScript with access to other object models. The WSH core object model is quite complex and may at first seem rather daunting. As a result, you may not leave this chapter feeling 100 percent confident that you fully understand it. But don't worry—you'll continue to develop your understanding of this complex topic as you go through the rest of this book.

start sidebar
Definition

An object model is a representation of a number of related objects that provide a script or program with the ability to view and interact with each of the objects (files, disks, printers, and so on) represented in the object model.

end sidebar

The Core Object Model

The WSH core object model provides programmatic access to Windows resources. There are 14 objects in the WSH core object model, as depicted in Figure 2.4. Each of these objects provides access to a particular category of Windows resources.

click to expand
Figure 2.4: The WSH core object model consists of 14 objects, all of which have properties and methods that expose various parts of the Windows operating system.

At the top, or root , of the WSH core object model is the WScript object. It is from this object that all other objects are instantiated. The WScript object is automatically established during the startup of the execution host and can therefore be referenced without first being instantiated within your scripts. For example, let's create a short one-line script called Greeting.vbs.

WScript.Echo "This is an example of the use of WScript object's Echo() method"

To test this script, open your script editor and type in this statement. Now save the script, then run it by double-clicking it. The popup dialog, shown in Figure 2.5, should appear. As this script demonstrates , you can automatically access any of the properties and methods belonging to the WScript object directly from within your scripts.


Figure 2.5: A popup dialog created using the WScript object's Echo() method

The WScript object provides access to a number of very useful methods that you'll see used throughout this book. These methods include

  • CreateObject() . Establishes an instance of the specified object.

  • DisconnectObject() . Prevents a script from accessing a previously instantiated object.

  • Echo() . Displays a text message in the Windows Console or as a popup dialog depending on which execution hosts runs the script.

  • Quit() . Terminates a script's execution.

  • Sleep() . Pauses the execution of a script for a specified number of seconds.

start sidebar
Definition

Instantiation is a term that describes the process of creating a reference to an object. In order to work with an object you must first create, or instantiate, a reference to it within your scripts.

end sidebar

The WScript object is referred to as a public or exposed object. The WSH core object model has three other public objects. These are the WshController , WshShell , and WshNetwork objects. Each of these three objects must be instantiated within your scripts using the WScript object's CreateObject() method. All of the other objects in the WSH core object model can only be instantiated by using properties or methods associated with the WScript , WshController , WshShell , and WshNetwork objects.

Table 2.1 lists the rest of the objects in the WSH core object model, as well as the object properties or methods required to instantiate them.

Table 2.1: WORKING WITH LOWER-LEVEL WSH OBJECTS

Object

Method of Instantiation

WshArguments

WScript.Arguments

WshNamed

WScript.Arguments.Named

WshUnnamed

WScript.Arguments.Unnamed

WshRemote

WshController.CreateScript()

WshRemoteError

WshRemote.Error

WshShortcut

WshShell.CreateShortcut()

WshUrlShortcut

WshShell.CreateShortcut()

WshEnvironment

WshShell.Environment

WshSpecialFolders

WshShell.SpecialFolders

WshScriptExec

WshShell. Exec ()

WSH Objects and Their Properties and Methods

Each object in the WSH core object model provides access to, or exposes, a particular subset of Windows functionality. Table 2.2 lists all 14 of the WSH core objects, provides a high-level description of these objects, and lists all of the properties and methods associated with each object.

Table 2.2: WSH CORE OBJECTS

Object

Description

WScript

This is the WSH root object. It provides access to a number of useful properties and methods. It also provides access to the rest of the objects in the WSH core object model.

Properties: Arguments , FullName , Interactive , Name , Path , ScriptFullName , ScriptName , StdErr , StdIn , StdOut , and Version .

Methods: ConnectObject() , CreateObject() , DisconnectObject() , Echo() , GetObject() , Quit() , and Sleep() .

WshArguments

This object allows you to access command-line arguments passed to the script at execution time.

Properties: Count , Item , and Length , Named and Unnamed .

Methods: Count() and ShowUsage() .

WshNamed

This object provides access to a set of named command-line arguments.

Properties: Item and Length .

Methods: Count() and Exists() .

WshUnnamed

This object provides access to a set of unnamed command-line arguments.

Properties: Item and Length .

Methods: Count() .

WshController

This object provides the ability to create a remote script process.

Properties: This object does not support any properties.

Methods: CreateScript .

WshRemote

This object provides the ability to administrator remote computer systems using scripts over a network.

Properties: Status and Error .

Methods: Execute() and Terminate() .

WshRemoteError

This object provides access to information on errors produced by remote scripts.

Properties: Description , Line , Character , SourceText , Source and Number .

Methods: This object does not support any methods.

WshNetwork

This object provides access to a number of different network resources such as network printers and drives.

Properties: ComputerName , UserDomain , and UserName .

Methods: AddWindowsPrinterConnection (), AddPrinterConnection() , EnumNetworkDrives() , EnumPrinterConnection() , MapNetworkDrive() , RemoveNetworkDrive() , RemovePrinterConnection() , and SetDefaultPrinter() .

WshShell

This object provides access to the Windows registry, event log, environmental variables , shortcuts, and applications.

Properties: CurrentDirectory , Environment and SpecialFolders .

Methods: AppActivate() , CreateShortcut() , ExpandEnv ironmentStrings() , LogEvent() , Popup() , RegDelete() , RegRead() , RegWrite() , Run() , SendKeys() , and Exec() .

WshShortcut

This object provides scripts with methods and properties for creating and manipulating Windows shortcuts.

Properties: Arguments , Description , FullName , Hotkey , I conLocation , TargetPath , WindowStyle , and WorkingDirectory .

Methods: Save() .

WshUrlShortcut

This object provides scripts with methods and properties for creating and manipulating URL shortcuts.

Properties: FullName and TargetPath .

Methods: Save() .

WshEnvironment

This object provides access to Windows environmental variables.

Properties: Item , and Length .

Methods: Remove() and Count() .

WshSpecialFolders

This object provides access to special Windows folders that allow scripts to configure the Start Menu, desktop, Quick Launch Toolbar, and other special Windows folders.

Properties: Item .

Methods: Count() .

WshScriptExec

This object provides access to error information from scripts run using the Exec method.

Properties: Status , StdOut , StdIn and StdErr .

Methods: Terminate() .

The number of properties and methods supported by objects in the WSH core object model is too extensive to include them all in this table; I will cover them separately a little later in this chapter.

Examining Object Properties

By accessing object properties, your scripts can gather all kinds of information when they execute. For example, using the properties associated with the WshNetwork object, your scripts can collect information about the Windows domain that the person who ran the script has logged in to, as well as the computer's name and the user 's name. This information could then be used, for example, to prevent the script from executing on certain domains or computers.

There are over three dozen properties associated with various WSH objects. In many cases, properties may be associated with more than one object. Refer to Table 2.2 to see which properties are associated with which objects.

A complete review of WSH object properties is provided in Table 2.3.

Table 2.3: WSH OBJECT PROPERTIES

Property

Description

Arguments

Sets a pointer reference to the WshArguments collection.

AtEndOfLine

Returns either true or false depending on whether the end-of-line maker has been reached in the stream.

AtEndOfStream

Returns either true or false depending on whether the end of the input stream has been reached.

Character

Identifies the specific character in a line of code where an error occurs.

Column

Returns the current column position in the input stream.

ComputerName

Retrieves a computer's name.

CurrentDirectory

Sets or retrieves a script current working directory.

Description

Retrieves the description for a specified shortcut.

Environment

Sets a pointer reference to the WshEnvironment .

Error

Provides the ability to expose a WshRemoteError object.

ExitCode

Returns the exist code from a script started using Exec() .

FullName

Retrieves a shortcut or executable program's path .

HotKey

Retrieves the hotkey associated with the specified shortcut.

IconLocation

Retrieves an icon's location.

Interactive

Provides the ability to programmatically set script mode.

Item

Retrieves the specified item from a collection or provides access to items stored in the WshNamed object.

Length

Retrieves a count of enumerated items.

Line

Returns the line number for the current line in the input stream or identifies the line number within a script on which an error occurred.

Name

Returns a string representing the name of the WScript object.

Number

Provides access to an error number.

Path

Returns the location of the folder where the CScript or WScript execution hosts reside.

ProcessID

Retrieves the process ID (PID) for a process started using the WshScriptExec object.

ScriptFullName

Returns an executing script's path.

ScriptName

Returns the name of the executing script.

Source

Retrieves the identity of the object that caused a script error.

SourceText

Retrieves the source code that created the error.

SpecialFolders

Provides access to the Windows Start menu and desktop folders.

Status

Provides status information about a remotely executing script or a script starting with Exec() .

StdErr

Enables a script to write to the error output stream or provides access to read-only error output from an Exec object.

StdIn

Enables read access to the input stream or provides access to the write-only input stream for the Exec object.

StdOut

Enables write access to the output stream or provides access to the write-only output stream of the Exec object.

TargetPath

Retrieves a shortcut's path to its associated object.

UserDomain

Retrieves the domain name.

UserName

Retrieves the currently logged-on user's name.

Version

Retrieves the WSH version number.

WindowStyle

Retrieves a shortcut's window style.

WorkingDirectory

Returns the working directory associated with the specified shortcut.

Working with Object Properties

Now let's take a look at an example of a VBScript that demonstrates how to instantiate an instance of the WshNetwork object and access its properties. The script is called NetInfo.vbs and is as follows :

Set WshNtwk = WScript.CreateObject("WScript.Network") PropertyInfo = "User Domain" & vbTab & "= "& WshNtwk.UserDomain & vbCrLf & _ "Computer Name" & vbTab & "= "& WshNtwk.ComputerName & vbCrLf & _ "User Name" & vbTab & "= "& WshNtwk.UserName & vbCrLf MsgBox PropertyInfo, vbOkOnly , "WshNtwk Properties Example"

As you can see, it is not a very big script. It begins by using a Set statement to create an instance of the WshNetwork object, which is associated with a variable name of WshNtwk . Once you have established an instance of the WshNetwork object in this manner, you'll be able to reference the object's properties and methods using its variable name assignment.

start sidebar
Definition

The Set statement is used to create a reference to a specified object. Using this reference, you'll be able to refer to the object and its properties and methods over and over again throughout your script.

end sidebar

The next statement is so long, that to improve the script's readability, I decided to break it into three lines and end each of the first two lines with the & and _ characters . The & character is a concatenation character and is used to append two strings together. The _ character is a continuation character and is used to indicate that a statement is continued on the next line. This statement displayed the values of the following WshShell properties:

  • WshNetwork.UserDomain . The name of the domain into which the person running the script is logged in.

  • WshNetwork.ComputerName . The name of the computer on which the script is being executed.

  • WshNetwork.UserName . The username of the person who ran the script.

In order to improve the presentation of the message, I formatted it using the VBScript vbTab and vbCrLf constants. The vbTab constant was used to line up the output at the point of the equals sign. The vbCrLf constant was used to execute a line feed and carriage return at the end of each line of output.

start sidebar
Definition

A constant is a VBScript construct that contains information that does not change during the execution of a script. VBScript provides a collection of built-in constants, such as the vbTab and vbCrLf constants, that you can incorporate into your scripts to control the formatting of your script output.

end sidebar

The last thing that the script does is display the message using the following statement:

MsgBox PropertyInfo, vbOkOnly , "WshNetwork Properties Example"

MsgBox() is a built-in VBScript function that displays a text message in a popup dialog. PropertyInfo is a variable that I used to store the output message. VbOkOnly is a VBScript constant that tells the MsgBox() function to only display the OK button in the popup dialog. The last part of the previous statement is a message that will be displayed in the popup dialog's titlebar. If you save and run this script yourself, you should see a popup dialog similar to the one shown in Figure 2.6.


Figure 2.6: A popup dialog displaying properties associated with the WshNetwork object

Examining Object Methods

The WSH also provides a large collection of object methods. By using these methods in your VBScripts, you'll be able to manipulate the Windows resources associated with objects.

TRAP 

You won't be able to do anything with your VBScripts that you don't have the appropriate set of security permissions and rights to do on a particular computer. For example, if you don't have the ability to manually create a new user account on your computer, then you won't be able to run a VBScript designed to perform this operation, either. However, if you have administrative privileges on the computer, your scripts should be able to run unhindered.

For example, using the WshShell object's RegRead() , RegWrite() , and RegDelete() methods, you can create scripts that can access and manipulate the contents of the Windows registry. Using these methods, you can create scripts that can configure just about any Windows resource.

TRAP 

The Windows registry is a repository used by the operating system to store information about every aspect of the computer's hardware and software. Making an incorrect configuration change to the registry can have disastrous affects on the operation of the computer and may potentially prevent it from being able to start. I strongly recommend that, unless you're very sure of what you're doing, you never attempt to modify the registry, either manually or by using a script.

A complete review of WSH object methods is provided in Table 2.4.

Table 2.4: WSH OBJECT METHODS

Method

Description

AddPrinterConnection()

Creates printer mappings

AddWindowsPrinterConnection()

Creates a new printer connection

AppActivate()

Activates the targeted application Window

Close()

Terminates an open data stream

ConnectObject()

Establishes a connection to an object

Count

Retrieves the number of switches found in the WshNamed and WshUnnamed objects

CreateObject()

Creates a new instance of an object

CreateScript()

Instantiates a WshRemote object representing a script that is running remotely

CreateShortcut()

Creates a Windows shortcut

DisconnectObject()

Terminates a connection with an object

Echo()

Displays a text message

EnumNetworkDrives()

Enables access to network drives

EnumPrinterConnections()

Enables access to network printers

Exec()

Executes an application in a child command shell and provides access to the environment variables

Execute()

Initiates the execution of a remote script object

Exists()

Determines a specified key exists within the WshNamed object

ExpandEnvironmentStrings()

Retrieves a string representing the contents of the Process environmental variable

GetObject()

Retrieves an Automation object

GetResource()

Retrieves a resource's value as specified by the <resource> tag

LogEvent()

Writes a message in the Windows event log

MapNetworkDrive()

Creates a network drive mapping

Popup()

Displays a text message in a popup dialog

Quit()

Terminates, or ends, a script

Read()

Retrieves a string of characters from the input stream

ReadAll()

Retrieves the s string that is made up of the characters in the input stream

ReadLine()

Retrieves a string containing an entire line of data from the input stream

RegDelete()

Deletes a registry key or value

RegRead()

Retrieves a registry key or value

RegWrite()

Creates a registry key or value

Remove()

Deletes the specified environmental variable

RemoveNetworkDrive()

Deletes the connection to the specified network drive

RemovePrinterConnection()

Deletes the connection to the specified network printer

Run()

Starts a new process

Save()

Saves a shortcut

SendKeys()

Emulates keystrokes and sends typed data to a specified window

SetDefaultPrinter()

Establishes a default Windows printer

ShowUsage()

Retrieves information regarding the way that a script is supposed to be executed

Skip()

Skips x number of characters when reading from the input stream

SkipLine()

Skips an entire line when reading from the input stream

Sleep()

Pauses script execution for x number of seconds

Terminate()

Stops a process started by Exec()

Write()

Places a string in the output stream

WriteBlankLines()

Places a blank in the output stream

WriteLine()

Places a string in the output stream

Working with Object Methods

To really understand how object methods work you need to work with some examples. Let's take a look at two examples. In the first example, you'll see how to work with the WshShell object's Run() method in order to create a graphical front end to the Windows NET SEND command. In the second example, you'll learn how to use the WshShell object's LogEvent() method to write messages directly to a Windows XP, .NET, 2000, or NT computer's application event log.

The WshShell object provides access to a number of Windows resources, including

  • The Windows application log

  • The Windows registry

  • Any Windows command-line command

Let's look at an example of how to use the WshShell object's Run() method. I've named this VBScript NetMessenger.vbs. NetMessenger.vbs provides a friendly graphical front end to the Windows NET SEND command-line command. The NET SEND command can be used to send text messages over a network to other currently logged-on users by specifying either the user's username or the computer name that the user is using. To use this command from the Windows command line, you might type something like

NET SEND jford Jerry,

please

stop by my office and see me when you have a moment

NET SEND is the command being used. Jford is the username of the person to receive the message, and the rest of the statement is the message text that is to be sent.

Using the NET SEND command is not very complicated. Click on Start, Run, and then type CMD and click OK. This opens the Windows Console. Now type the NET SEND command and press the Enter key. That's it. Within moments, your message should appear on the recipient's screen. Unfortunately, many people are intimidated by the very thought of using the Windows Command Prompt. So let's write a VBScript, shown below, that makes using this command easy.

Set WshShl = WScript.CreateObject("WScript.Shell") Recipient = InputBox("Type the username or computer name "& _ "that the message is to be sent: ") MsgText = InputBox("Type your message: ") WshShl.Run "Net Send "& Recipient & " " & MsgText

The first line of this script instantiates the WshShell object and associates with it a variable called WshShl . The next two lines display a popup dialog asking the user to type a user name or computer name. The information typed in by the user is stored in a variable called Recipient . The next line allows the user to type in a text message and stores it in a variable called MsgText . The last line of this script executes the WshShell object's Run() method, passing it the NET SEND command, the name of the recipient, and the message to be sent.

Open your script editor and type in the script as just shown, then save it as Messenger.vbs. Run it and you'll see a popup dialog, like the one in Figure 2.7, asking for the user name or computer name of the recipient.

click to expand
Figure 2.7: Type the username or computer name to which you want to send a message.

Type the required information and click OK. The popup dialog shown in Figure 2.8 will appear. Type the message you wish to send and then click OK.

click to expand
Figure 2.8: Type the message that you wish to send.

Within a few moments your message will appear on the recipient's screen, as shown in Figure 2.9.


Figure 2.9: The recipient of the message will see your message, as well as your computer's name and the date and time of the message.

In the second example, you'll learn how to use the WshShell object's LogEvent() method to write a message to the Windows event log. The Windows event log is accessed differently, depending on which version of Windows you use. For example, on Windows 2000 and Windows XP, you can click Start and then right-click My Computer and select Manage to open the Computer Management console where the Event Viewer utility or snap-in resides. To view the application event log, expand the Event Viewer node and select Application, as shown in Figure 2.10. Then double-click on an event entry in the event log to examine it.

click to expand
Figure 2.10: Examining the contents of the application event log

TRAP 

Only the Windows .NET, XP, 2000, and NT operating systems support event logs. So don't try running this script on other Windows operating systems, such as Windows 98 or Me.

{% if main.adsdop %}{% include 'adsenceinline.tpl' %}{% endif %}

The scripting logic to write a message to the Windows application event log is very simple.

Set WshShl = WScript.CreateObject("WScript.Shell") WshShl.LogEvent 0, "EventLogger.vbs - Beginning script execution."

The first line of this script establishes an instance of the WshShell object. The second line uses the WshShell object's LogEvent() method to write a message to the event log.

TRICK 

One really good use of the WshShell object's LogEvent() method is to log the execution of scripts run using the Windows Event Scheduler service. This way, you can review the application event log each day and make sure that your scripts are executing when you expect them to.

Using your script editor, create a new script called EventLogger.vbs that contains the previous statements. Run the script and then check the application event log; you should find the message added by the script. Double-click it; you should see the Event Properties dialog for the event, as shown in Figure 2.11.

click to expand
Figure 2.11: Viewing the event that the EventLogger.vbs script added to the Windows application event log