Windows Script Host

Overview

Ask programmers if they use VBScript and most will answer 'Yes, for ASP' or 'Yes, for client-side scripting on an intranet.' But you need to remember that these are nothing more than contexts where VBScript can be used to solve problems that are in need of scripting solutions. Because VBScript is designed as an ActiveX Scripting engine, it can be used to provide scripting capability for any ActiveX Scripting host environment.

Two of the most common hosts are Active Server Pages (ASP) and Internet Explorer. Both of these hosts provide the programmer with a lot of power but both also come with certain limitations. An example is that Internet Explorer does not provide a capability for script to interact with the local computer (such as file system access, registry access, and so on) unless the user explicitly sets permissions for this (and doing this can cause enormous security risks. For this reason, this is usually done only for trusted sites and intranets ). So what's the point of having extended power within the VBScript language when you can't do anything with it? Well, this is where Windows Script Host (WSH) comes in. WSH is a totally scripting language-neutral host interface that will work with any ActiveX Scripting engine. This means that programmers that want to use WSH can use VBScript, JScript, PerlScript, or any other scripting language that exposes the ActiveX Scripting interfaces. The WSH host interface thus provides Windows platforms with a powerful, yet easy-to- use scripting platform that can be accessed from both the Windows GUI and the command prompt.

In this chapter, you will be examining the following aspects of WSH:

Tools of the Trade

In order to begin making use of WSH you will need the following:

If your operating system is Windows 98, Windows Me, Windows NT 4.0 with Option Pack 4 installed, Windows 2000, or Windows XP, then you probably already have Windows Script Host (WSH 1.0 is provided as an optional component for Win98 and WinNT). However, you may want to ensure that you have the latest version in order to run the scripts included in this chapter. You can download it from the Microsoft Scripting Technologies Web site at http://msdn.microsoft.com/scripting/ windowshost/ . We suggest that you upgrade to the latest version, WSH 5.6 and Windows Script engine 5.6 for JScript and VBScript.

In addition, you may wish to install the WSH references locally. The complete WSH reference is also available for download from http://msdn.microsoft.com/scripting/windowshost/ as a single HTML Help file.

What Is WSH?

Windows Script Host (WSH) is a Windows administration tool. WSH creates an environment for hosting scripts so that when a script arrives at a computer, WSH plays the part of the host. WSH makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, WSH manages security and invokes the appropriate script engine.

Since WSH is script language independent, WSH also provides the facility to write scripts in JScript, Perl, Python, REXX, or any other ActiveX Scripting Language (only the VBScript and JScript languages are available from Microsoft-other ActiveX Scripting engines are available from third parties).

WSH provides network administrators with a handy toolkit to use for access to machines scattered across a network of computers running various flavors of the Windows operating system family. Much of this access comes through the use of Active Directory Service Interfaces (ADSI) and Windows Management Instrumentation (WMI). ADSI provides a single set of COM interfaces that can be used with multiple directory services, such as the Lightweight Directory Access Protocol (LDAP), the Windows NT directory service, and Novell's Netware and NDS services. WMI is Microsoft's implementation of Web-Based Enterprise Management (WBEM), a standard method of providing access to management information such as applications installed on a given client, system memory, and other client information.

By developing WSH scripts that take advantage of ADSI and WMI, administrators can develop scripts that make it very easy to perform the following tasks and much more:

As the table shown previously shows, Q1 the current version of WSH is version 5.6. This version was released with the release of Windows XP and brings with it significant changes over the previous version (version 2.0). The current release of WSH now includes a whole host of features that programmers will find appealing:

WSH 1.0 operated by simply associating the file extensions for VBScript ( .vbs ) and JScript ( .js ) files with the actual script host. This meant that if you double-clicked on a script file, it would automatically execute. However, this had one major limitation-the association model did not allow for the use of code modules or for the integrating of multiple script languages in a single WSH script project. To appease programmers everywhere, Microsoft introduced a new type of script file ( .wsf ) in WSH 2.0, which utilized an XML syntax that provides much of the new functionality listed earlier.

This schema includes the tags < script >, < object >, and < job > among others. You'll be seeing how this all works later on in this chapter.

Tip  

The file extension .wsf is only available with final release of WSH 2.0 and later. Developers working with the beta releases of WSH 2.0 will have to use the .ws file extension. We suggest that you upgrade to the version 5.6 script engines and WSH.

Types of Script Files

Stand-alone script files come in a few different formats, each having its own extension. The following table is a list of some common types.

The script type that you choose will ultimately depends on your needs. Most small projects only require the use of one file type while certain scenarios will mean that you could divide your overall problem into several smaller parts , writing a separate script for each part, with each script written in the most suitable scripting language.

Extension Script Type Description

.bat

MS-DOS batch file

MS-DOS operating system batch file

.asp

ASP page

Active Server Page file

.htm

HTML file

Web page

.html

HTML file

Web page

.js

JScript file

Windows script

.vbs

VBScript file

Windows script

.wsf

Windows Script Host file

Container or project file for a Windows script. This is supported by WSH 2.0 and later

.wsh

Windows Script Host file

Property file for a script file; supported by WSH 1.0 and later

This is where Windows Script Host files (WSF files) are useful. WSF files may include other script files as part of the script. This means that multiple WSF files can reference libraries of useful functions, which may be created and stored in a single place.

Running Scripts with the Windows Script Host

WSH provides two interfaces that allow us to execute scripts on the command line or from within the Windows environment. These two interfaces each use different host programs for the VBScript engine:

The reason there are two host programs is that cscript.exe is designed for use from a console window (basically, an MS-DOS box within Windows) while wscript.exe is intended to interface directly with the Windows GUI itself. There is very little difference between them in terms of functionality.

Command Line Execution

The console interface for executing script files, cscript.exe , is called as follows :

Open the Run dialog ( Start Run ) or a command window (in Windows 9x, this is done via Start Programs DOS Prompt; in Windows NT via Start Programs Command Prompt; and in XP via Start All Programs Accessories Command Prompt ).

Execute your script as follows.

cscript c:folderNameYourScriptName.vbs

If you run cscript.exe with no arguments directly from an MS-DOS window, you will simply get the usage notes, as shown in Figure 12-1.

Figure 12-1

The usage syntax is as follows.

cscript scriptname.extension [option...] [arguments...]

The following command-line options are provided by cscript.exe to allow you to control various settings for the WSH environment.

//B

Batch mode. This suppresses script errors and prompts from being displayed

//D

Enable active debugging

//E:engine

Use engine for executing script

//H:Cscript

Changes the default script host to cscript.exe

//H:Wscript

Changes the default script host to wscript.exe (default)

//I

Interactive mode (default, opposite of //B )

//Job:xxxx

Execute a WSF job

//Logo

Display logo (default)

//Nologo

Prevent logo from displaying. No banner will be shown at execution time

//S

Save current command line options for this user

//T:nn

Time out in seconds. Maximum time a script is permitted to run

//X

Execute script in debugger

//U

Use Unicode for redirected I/O from the console

To use these, add them as switches at the command line. The following example executes the script in the debugger.

cscript MyScript.vbs //X

Execution of WSH within the Windows Environment

The Windows GUI interface for script file execution, wscript.exe , allows us to execute files in several ways:

From the Run dialog, you can invoke wscript.exe .

wscript c:folderNameYourScriptName.vbs

If you run wscript.exe from an MS-DOS window, you'll get no output in the MS-DOS window. Instead you'll see the dialog box shown in Figure 12-2, which provides minimal customization options. This is the same dialog box displayed if wscript.exe is run from the Run command dialog.

When you click OK , nothing happens. The only way to customize script behavior on a system level is through the cscript options detailed earlier. This dialog is used for individual script customization through .wsh files, which we'll cover next . The major difference between cscript and wscript really becomes apparent only when debugging a faulty script. This is because sending error messages to a console window is much quicker and easier to handle than perhaps endless error pop-ups produced by wscript . We'd recommend cscript for use when debugging scripts, and it is best to use the Echo method of the WScript object when printing debug output, as this can result in too many error messages being generated. In fact, it is possible that you get into loops where you can't exit from the error messages.

Using WSH Files to Launch Scripts

Maybe you don't need or want to modify the settings for every script you execute, but you do need to be able to control individual files. This is made possible by creating control files, which have the extension .wsh , that allow us to control settings for individual scripts. A .wsh file is a small configuration file roughly following the .ini file format of past Windows versions. These files are good for customizing the way a script is started up-you can have several different .wsh files for the one script.

Figure 12-2

To create a .wsh file, right-click on a file associated with WSH (a file with a .js, .vbs , or .wsf extension), select Properties , and then the Script tab from the dialog box as shown in Figure 12-3.

Figure 12-3

This dialog box allows you to change the time-out default setting, and whether or not logo information should be displayed when the script is executed on the command line. When you apply or accept any changes you have made, a new file will be created, with the same name as the script in question, but containing the extension .wsh . This new file will record these custom settings in a format which the host engines use to set runtime options. Here is a .wsh file created from a script named test.vbs .

[ScriptFile] Path=C: est.vbs [Options] Timeout=25 DisplayLogo=0

In order to execute the script with these options, you would run the test.wsh file.

Windows Script Host Intrinsic Objects

Every programming environment provides its own object model that developers can use to implement solutions, and WSH is no different. WSH contains a core set of objects, that in turn contains properties and methods , which can be used to access other computers on a network, import external scriptable objects for use within an application, or connect with Windows or the Windows shell.

The WScript Object

The root of the WSH object model is the WScript object. This object provides properties and methods that give the developer access to a variety of information, such as:

WScript Properties

What follows are the properties for the WScript object. The WScript object has 11 properties:

Arguments

The Arguments property contains the WshArguments object (a collection of arguments). Use a zero-based index to retrieve individual arguments from this collection.

Set objArgs = WScript.Arguments For x = 0 to objArgs.Count - 1 WScript.Echo objArgs(x) Next

FullName

The FullName property is a read-only string representing the fully qualified path of the host executable file ( cscript.exe or wscript.exe ). The following code uses the FullName property.

WScript.Echo WScript.FullName

This produces the output shown in Figure 12-4.

Figure 12-4

Interactive

The Interactive property sets the script mode, or identifies the script mode. When used, this property returns a Boolean value. There are two possible modes available for use. These are batch and interactive.

In interactive mode (the default), the script provides user interaction. Input to and output from the WSH is enabled and the script can echo information to dialog boxes and can wait for the user to provide feedback. In batch mode, this type of user interaction is not supported and all input and output to WSH is disabled.

Script mode can be set using the WSH command-line switches //I (for interactive) and //B (for batch).

Name

The Name property returns the name of the WScript object (the host executable file). This is a read-only string. The following code uses the Name property.

WScript.Echo WScript.Name

This produces the output shown in Figure 12-5.

Figure 12-5

Path

The Path property returns the name of the directory containing the host executable file ( cscript.exe or wscript.exe ). This returns a read-only string.

The following VBScript code echoes the directory where the executable file resides.

WScript.Echo WScript.Path

ScriptFullName

The ScriptFullName property returns the full path of the currently running script. This property returns a read-only string.

ScriptName

The ScriptName property returns the file name of the currently running script. This property returns a read-only string. The following code echoes the name of the script being run, as shown in Figure 12-6.

WScript.Echo WScript.ScriptName

Figure 12-6

StdErr

The StdErr property exposes the write-only error output stream for the current script. It returns an object representing the standard error stream. The StdIn , StdOut , and StdErr , streams can be accessed while using cscript.exe only. Note that attempting to access these streams while using wscript.exe produces an error.

StdIn

The StdIn property exposes the read-only input stream for the current script. It returns an object representing the standard error stream. The StdIn , StdOut , and StdErr streams can be accessed while using cscript.exe only. Note that attempting to access these streams while using wscript.exe produces an error.

StdOut

The StdOut property exposes the write-only error output stream for the current script. It returns an object representing the standard error stream. The StdIn , StdOut , and StdErr streams can be accessed while using cscript.exe only. Note that attempting to access these streams while using wscript.exe produces an error.

The following example makes use of all three of the built-in stream types to print a list of all files matching a particular extension. This is implemented by piping the output from the DOS dir command into the filter script, with an extension string passed as an argument.

' Usage: dir cscript filter.vbs ext ' ext: file extension to match ' Dim streamOut, streamIn, streamErr Set streamOut = WScript.StdOut Set streamIn = WScript.StdIn Set streamErr = WScript.StdErr Dim strExt, strLineIn Dim intMatch strExt = WScript.Arguments(0) intMatch = 0 Do While Not streamIn.AtEndOfStream strLineIn = streamIn.ReadLine If 0 = StrComp(strExt, Right(strLineIn, Len(strExt)), _ vbTextCompare) Then streamOut.WriteLine strLineIn intMatch = intMatch + 1 End If Loop If 0 = intMatch Then streamErr.WriteLine "No files of type '" & strExt & "' found" End If

Since this example uses StdIn , StdOut , and StdErr for all messaging, you could use it not only to print out matching files to the screen, but also to send output to a text file or another application with redirection or additional piping. For example, you could create a file containing all .vbs files in an entire directory tree, including all subdirectories, with the following command.

C:wsh>dir /s cscript filter.vbs vbs >> vbsfiles.txt

Version

This property returns the version of WSH. The following code echoes the current version of WSH, as shown in Figure 12-7.

WScript.Echo WScript.Version

Figure 12-7

WScript Methods

What follows is a listing of the WScript methods. The WScript object has seven methods:

CreateObject

This method of the WScript object is used to create a COM object.

object.CreateObject(strProgID[,strPrefix])

Objects created with the CreateObject method using the strPrefix argument are connected objects. The object's outgoing interface is connected to the script file after the object is created. Event functions are a combination of this prefix and the event name.

If you create an object and do not provide the strPrefix argument, you can still synchronize events on the object by using the ConnectObject method. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name.

The following code uses the CreateObject method to create a WshNetwork object.

Set WshNetwork = WScript.CreateObject("WScript.Network")

ConnectObject

This method connects the object's event sources to functions with a given prefix.

object.ConnectObject(strObject, strPrefix)

Connected objects are useful when you want to synchronize an object's events. The ConnectObject method connects the object's outgoing interface to the script file after creating the object. Event functions are a combination of this prefix and the event name.

WScript.ConnectObject RemoteScript, "remote_"

DisconnectObject

This is used to disconnect a connected object's event sources.

object.DisconnectObject(obj)

Disconnecting an object means that WSH will no longer respond to its events. It is important to note though that the object is still capable of firing events. Note also that the DisconnectObject method does nothing if the specified object is not already connected.

WScript.DisconnectObject RemoteScript

Echo

This outputs text to either a message box or the command console window.

object.Echo [Arg1] [,Arg2] [,Arg3] ...

The Echo method gives a different type of output depending on which WSH engine you are using.

WSH Engine Text Output

wscript.exe

Graphical message box

cscript.exe

Command console window

Figures 12-8 and 12-9 show an example of each output.

GetObject

The GetObject method retrieves an existing object with the specified ProgID , or creates a new one from a file.

object.GetObject(strPathname [,strProgID], [strPrefix])

Figure 12-8

Figure 12-9

You use the GetObject method when an instance of the object exists in memory or when you want to create the object from a file. The GetObject method can be used with all COM classes, independent of the scripting language used to create the object.

If no current instance exists and you do not want the object created from a file, use the CreateObject method.

Dim MyObject As Object Set MyObject = GetObject("C:DRAWINGSSCHEMA.DRW") MyApp = MyObject.Application

Quit

This method forces the script execution to immediately stop at any time.

object.Quit([intErrorCode])

The Quit method can be used to return an optional error code. If the Quit method is the final instruction in your script (and you have no need to return a nonzero value), you can leave it out, and your script will terminate normally.

WScript.Quit 1 ' This line of code is not executed. MsgBox "This message will never be shown!"

Here is another example of the Quit method in action.

If Err.Number <> 0 Then WScript.Quit 1 ' some failure indicator Else WScript.Quit 0 ' success End If WScript.Quit 1

Sleep

This method suspends script execution for a specified length of time, and then continues execution.

object.Sleep(intTime)

When using this method the thread running the script is suspended and CPU utilization is released. Execution resumes when the interval expires . To be triggered by an event, a script must be continually active because a script that has finished executing will certainly not detect an event. Events handled by the script will still be executed during a sleep.

Passing the Sleep method a or - 1 will not cause a script to be suspended indefinitely.

 

The WshArguments Object

The use of arguments in programming tasks is a very useful mechanism for providing your script with input on which it can act. Think about working at a DOS prompt. Most command-line executable files use arguments in order to determine the right thing to do. For example, navigating within a directory structure.

c:>cd wsh

In this instance, cd is the name of a DOS command (for change directory), while wsh is the name of the directory activated-it is an argument passed to cd .

Creating scripts that work with arguments is a good step toward writing reusable code. Developers creating scripts designed to execute on the command line may immediately see the benefits of working with the Arguments property. However, within WSH, there is another good reason to use this object, as this is how drag-and-drop functionality is implemented.

A final justification for the use of this object is that it allows developers to reuse script code within other scripts, by running the script in question as if it were executing on the command line, passing whatever arguments may be necessary at runtime.

Accessing the WshArguments Object

This is accessed by using WScript.Arguments property.

Set objArgs = WScript.Arguments

WshArguments Properties

The WshArguments object is a collection returned by the WScript object's Arguments property ( WScript.Arguments ).

There are three ways to access sets of command-line arguments:

The following example simply loops through the WshArguments collection, displaying each in turn.

Set objArgs = WScript. Arguments For x = 0 to objArgs.Count - 1 WScript.Echo objArgs(x) Next

The interesting thing here is that this works in both cscript and wscript . You can try this out for yourself using the echoargs.vbs example. Execute on the command line, passing a few arguments:

c:vbsechoargs hello there

Figure 12-10 shows the output from the command line.

Figure 12-10

Now try dragging a file or two, then dropping them on echoargs.vbs . Figure 12-11 shows the output resulting from this.

Figure 12-11

The WshShell Object

Windows Script Host provides a convenient way to gain access to system environment variables , create shortcuts, access Windows special folders such as the Windows Desktop, and add or remove entries from the registry. It is also possible to create more customized dialog boxes for user interaction by using features of the Shell object.

Accessing the WshShell Object

Programmers should create an instance of the object WScript.Shell in order to be able to work with the properties listed in the next section. Further references to the WshShell object will refer to this created instance.

Set WshShell= WScript.CreateObject( "WScript.Shell" )

WshShell Properties

The WshShell object has three properties:

CurrentDirectory

This property retrieves or changes the current active directory.

object.CurrentDirectory

The CurrentDirectory property returns a string that contains the fully qualified path of the current working directory of the active process.

Dim WshShell Set WshShell = WScript.CreateObject("WScript.Shell") WScript.Echo WshShell.CurrentDirectory

Environment

This property returns the WshEnvironment object (a collection of environment variables).

object.Environment ([strType])

The Environment property contains the WshEnvironment object (a collection of environment variables). If strType is supplied, it specifies where the environment variable resides with possible values of:

If strType is not supplied, the Environment property returns different environment variable types depending on the operating system.

Type of Environment Variable Operating System

System

Microsoft Windows NT/2000/XP

Process

Windows 95/98/Me

For Windows 95/98/Me, only one strType is permitted, Process . None of the others can be used in scripts.

The following table lists some of the variables that are provided with the Windows operating system.

Name Description System User Process (NT/200 0/XP) Process (95/98/Me)

NUMBER_OF_PROCESSORS

Number of processors running on the machine.

x

-

X

-

PROCESSOR_ARCHITECTURE

Processor type of the user's workstation.

x

-

X

-

PROCESSOR_IDENTIFIER

Processor ID of the user's workstation.

x

-

X

-

PROCESSOR_LEVEL

Processor level of the user's workstation.

x

-

X

-

PROCESSOR_REVISION

Processor version of the user's workstation.

x

-

X

-

OS

Operating system on the user's workstation.

x

-

X

-

COMSPEC

Operating system on the user's workstation.

-

-

X

x

HOMEDRIVE

Primary local drive (usually this is C drive).

-

-

X

-

HOMEPATH

Default directory for users.

-

-

X

-

PATH

Path environment variable.

x

x

X

x

PATHEXT

Extensions for executable files (typically .com , .exe , .bat , or .cmd ).

x

-

X

-

PROMPT

Command prompt (typically $P$G ).

-

-

X

x

SYSTEMDRIVE

Local drive on which the system directory resides (typically c: ).

-

-

X

-

SYSTEMROOT

System directory (for example, c: winnt). This is the same as WINDIR .

-

-

X

-

WINDIR

System directory (for example, c: ). This is the same as SYSTEMROOT .

x

-

X

x

TEMP

Directory for storing temporary files (for example, c: emp ).

-

x

X

x

TMP

Directory for storing temporary files (for example, c: emp) .

-

x

X

x

Note that scripts can access environment variables that have been set by other applications and that none of the variables listed above are available from the Volatile type.

Here is an example of how to use the variables listed in the table in your code. This returns the number of processors present on the system.

Set WshShell = WScript.CreateObject("WScript.Shell") Set WshSysEnv = WshShell.Environment("SYSTEM") WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")

SpecialFolders

This property returns a SpecialFolders object (a collection of special folders).

object.SpecialFolders(objWshSpecialFolders)

The WshSpecialFolders object is a collection. This contains the entire set of Windows special folders, which include the Desktop folder, the Start Menu folder, and the My Documents folder.

The special folder name is used to index into the collection to retrieve the special folder you want. The SpecialFolders property returns an empty string if the requested folder ( strFolderName ) is not available. For example, Windows 95 does not have an AllUsersDesktop folder and returns an empty string if strFolderName is AllUsersDesktop .

The following special folders are available:

WshShell Methods

The WshShell object has 11 methods. All these methods relate to the operating system shell and allow you control over the Windows registry, as well as being able to create pop-ups and shortcuts and activate and control running applications:

AppActivate

Here you have a method that allows you to activate a specific application window already open .

object.AppActivate title

The AppActivate method returns a Boolean value that identifies whether the procedure call is successful. This method is used to change the focus to the named application or window. It does not affect whether it is maximized or minimized. Focus moves away from the activated application window when the user takes action to change the focus (or closes the window).

To determine which application to activate, the specified title is compared to the title string of each running application. If no exact match exists, any application whose title string begins with title is activated. If an application still cannot be found, any application whose title string ends with title is activated. If more than one instance of the application named by title exists, one instance is arbitrarily activated. You do not have control over which one is chosen .

 

CreateShortcut

This method can be used to either create a new shortcut or open an existing shortcut.

object.CreateShortcut(strPathname)

The CreateShortcut method returns either a WshShortcut object or a WshURLShortcut object. Calling the CreateShortcut method does not result in the creation of a shortcut. Instead, the shortcut object and changes you may have made to it are stored in memory until you save it to disk using the Save method. To create a shortcut, you must follow these steps:

A common cause of problems is putting arguments in the TargetPath property of the shortcut object. This will not work. All arguments to the shortcut must be put in the Arguments property.

 

ExpandEnvironmentStrings

This method returns an environment variable's expanded value.

object.ExpandEnvironmentStrings(strString)

This method expands environment variables defined in the PROCESS environment space only. Environment variable names must be enclosed between "% ' characters and are not case-sensitive.

set WshShell = WScript.CreateObject("WScript.Shell") WScript.Echo "The path to WinDir is " _ & WshShell.ExpandEnvironmentStrings("%WinDir%")

LogEvent

The LogEvent method adds an event entry to a log file.

object.LogEvent(intType, strMessage [,strTarget])

This method is used to return a Boolean value ( True if an event is successfully logged, otherwise False ). In Windows NT/2000/XP, events are logged in the Windows NT Event Log. In Windows 9x/Me, events are logged in WSH.log (which is located in the Windows directory).

There are six event types.

Type Value

SUCCESS

1

ERROR

2

WARNING

4

INFORMATION

8

AUDIT_SUCCESS

16

AUDIT_FAILURE

Set WshShell = WScript.CreateObject("WScript.Shell") 'assume that rS contains a return code 'from another part of the code if rS then WshShell.LogEvent 0, "Script Completed Successfully" else WshShell.LogEvent 1, "Script failed" end if

Popup

This method is used to display text in a pop-up message box.

intButton = object.Popup(strText,[nSecondsToWait],[strTitle],[nType])

The Popup method is used to display a message box regardless of which host executable file is running the script ( wscript.exe or cscript.exe ).

If nSecondsToWait is equal to zero (the default), the pop-up message box remains visible until it is closed by the user. If nSecondsToWaitis is greater than zero, the pop-up message box closes after nSecondsToWait seconds.

If you don't supply the argument strTitle , the title of the pop-up message box is set to the default string "Windows Script Host" .

The function of nType is the same as in the Microsoft Win32 application programming interface MessageBox function. The following tables show the values and their meanings. To get different results you can combine various values from these tables.

To display text properly in RTL (Right-to-Left) languages such as Hebrew or Arabic, add hex & h00100000 (decimal 1048576 ) to the nType parameter.

Button Types

Value Description

Show the OK button

1

Show the OK and Cancel buttons

2

Show the Abort , Retry , and Ignore buttons

3

Show the Yes , No , and Cancel buttons

4

Show the Yes and No buttons

5

Show Retry and Cancel buttons

Icon Types

Value Description

16

Show the Stop Mark icon

32

Show the Question Mark icon

48

Show the Exclamation Mark icon

64

Show the Information Mark icon

The return value intButton denotes the number of the button that the user clicked on. If the user does not click a button before nSecondsToWait seconds, intButton is set to -1.

Value Description

1

OK button

2

Cancel button

3

Abort button

4

Retry button

5

Ignore button

6

Yes button

7

No button

Dim WshShell, BtnCode Set WshShell = WScript.CreateObject("WScript.Shell") BtnCode = WshShell.Popup("Do you like this code?", 7, "Quick survey:", 4 + 32) Select Case BtnCode case 6 WScript.Echo "Glad to hear it - Thanks!" case 7 WScript.Echo "I'm sorry you didn't like it." case -1 WScript.Echo "Helllloooooooo?" End Select

RegDelete

This method deletes a key or one of its values from the registry.

object.RegDelete(strName)

You can specify a key name by ending strName with a final backslash or leave it out to specify a value name.

Fully qualified key names and value names are prefixed with a root key. You can also use abbreviated versions of root key names with the RegDelete method.

The five possible root keys you can use are listed in the following table.

Root Key Name Abbreviation

HKEY_CURRENT _ USER

HKCU

HKEY_LOCAL_MACHINE

HKLM

HKEY_CLASSES_ROOT

HKCR

HKEY_USERS

HKEY_USERS

HKEY_CURRENT_CONFIG

HKEY_CURRENT_CONFIG

The script that follows creates, reads, and then deletes Windows registry keys. The highlighted part of the script does the key deleting.

Dim WshShell, bKey Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.RegWrite "HKCUSoftwareWROXVBScript", 1, "REG_BINARY" WshShell.RegWrite "HKCUSoftwareWROXVBScriptProgRef","VBS_is_great","REG_SZ" bKey = WshShell.RegRead("HKCUSoftwareWROXVBScript") WScript.Echo WshShell.RegRead("HKCUSoftwareWROXVBScriptProgRef") WshShell.RegDelete "HKCUSoftwareWROXVBScriptProgRef" WshShell.RegDelete "HKCUSoftwareWROXVBScript" WshShell.RegDelete "HKCUSoftwareWROX"

Tip  

It is vitally important to take great care when modifying registry settings. Making incorrect changes to the registry can cause your system to become unstable or render it completely unusable. If you have any doubts about the inner workings of the registry, you are strongly advised to do some reading on the subject before beginning to experiment on your own.

RegRead

This method returns the value of a key or value name from the registry.

object.RegRead(strName)

The RegRead method returns values of the following five types.

Type Description In the Form of

REG_SZ

A string

A string

REG_DWORD

A number

An integer

REG_BINARY

A binary value

A VBArray of integers

REG_EXPAND _ SZ

An expandable string for example, %windir%\notepad.exe )

A string

REG_MULTI _ SZ

An array of strings

A VBArray of strings

You can specify a key name by ending strName with a final backslash or leave it off to specify a value name.

A value entry consists of three parts :

When you specify a key name (as opposed to a value name) RegRead returns the default value. To read a key's default value, specify the name of the key.

Fully qualified key names and value names begin with a root key. You can also use abbreviated versions of root key names with the RegRea d method. The five possible root keys are listed in the following table.

Root Key Name Abbreviation

HKEY_CURRENT_USER

HKCU

HKEY_LOCAL_MACHINE

HKLM

HKEY_CLASSES _ ROOT

HKCR

HKEY_USERS

HKEY_USERS

HKEY_CURRENT_CONFIG

HKEY_CURRENT_CONFIG

The script that follows creates, reads, and then deletes Windows registry keys. The highlighted part of the script does the key reading.

Dim WshShell, bKey Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.RegWrite "HKCUSoftwareWROXVBScript", 1, "REG_BINARY" WshShell.RegWrite "HKCUSoftwareWROXVBScriptProgRef","VBS_is_great","REG_SZ" bKey = WshShell.RegRead("HKCUSoftwareWROXVBScript") WScript.Echo WshShell.RegRead("HKCUSoftwareWROXVBScriptProgRef") WshShell.RegDelete "HKCUSoftwareWROXVBScriptProgRef" WshShell.RegDelete "HKCUSoftwareWROXVBScript" WshShell.RegDelete "HKCUSoftwareWROX"

RegWrite

This method creates a new key, adds another value name to an existing key (and assigns it a value), or changes the value of an existing value name.

object.RegWrite(strName, anyValue [,strType])

You can specify a key name by ending strName with a final backslash. Do not include the final backslash to specify a value name.

The RegWrite method automatically converts the parameter anyValue to either a string or an integer while the value of strType determines its data type (either a string or an integer) The following table lists the options available for the strType method.

Converted to StrType

String

REG_SZ

String

REG_EXPAND _ SZ

Integer

REG_DWORD

Integer

REG_BINARY

The REG_MULTI_SZ type is not supported for the RegWrite method.

RegWrite will write at most one DWORD to a REG_BINARY value. Larger values are not supported with this method. Fully qualified key names and value names are prefixed with a root key. You can use abbreviated versions of root key names with the RegWrite method. The five root keys of the Windows registry are listed in the following table.

Root Key Name Abbreviation

HKEY_CURRENT_USER

HKCU

HKEY_LOCAL_MACHINE

HKLM

HKEY_CLASSES_ROOT

HKCR

HKEY_USERS

HKEY_USERS

HKEY_CURRENT_CONFIG

HKEY_CURRENT_CONFIG

The four possible data types you can specify with strType are listed in the following table.

Type Description In the Form of

REG_SZ

A string

A string

REG_DWORD

A number

An integer

REG_BINARY

A binary value

A VBArray of integers

REG_EXPAND_SZ

An expandable string (for example, %windir% \notepad.exe

A string

Dim WshShell, bKey Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.RegWrite "HKCUSoftwareWROXVBScript", 1, "REG_BINARY" WshShell.RegWrite "HKCUSoftwareWROXVBScriptProgRef","VBS_is_great","REG_SZ" bKey = WshShell.RegRead("HKCUSoftwareWROXVBScript") WScript.Echo WshShell.RegRead("HKCUSoftwareWROXVBScriptProgRef") WshShell.RegDelete "HKCUSoftwareWROXVBScriptProgRef" WshShell.RegDelete "HKCUSoftwareWROXVBScript" WshShell.RegDelete "HKCUSoftwareWROX"

Note  

It is vitally important to take great care when modifying registry settings. Making incorrect changes to the registry can cause your system to become unstable or render it completely unusable. If you have any doubts about the inner workings of the registry, you are strongly advised to do some reading on the subject before beginning to experiment on your own.

Run

The Run method runs a program in a new process.

object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])

The Run method returns an integer. The Run method starts a program running in a new Windows process. You can have your script wait for the program to finish executing before it continues, which allows you to run scripts and programs synchronously. If a file type has been properly registered to a particular program, calling Run on a file of that type executes the program. For example, calling Run on a *.txt file starts Notepad and loads the text file into it. The following table lists the available settings for intWindowStyle .

IntWindowStyle Description

Hides the window and activates another window.

1

Activates and displays a window.

If the window is minimized or maximized, the system restores it to its original size and position.

An application should specify this flag when displaying the window for the first time.

2

Activates the window and displays it as a minimized window.

3

Activates the window and displays it as a maximized window.

4

Displays a window in its most recent size and position.

The active window remains active.

5

Activates the window and displays it in its current size and position.

6

Minimizes the specified window and activates the next top-level window in the Z order.

7

Displays the window as a minimized window.

 

The active window remains active.

8

Displays the window in its current state.

The active window remains active.

9

Activates and displays the window.

If the window is minimized or maximized, the system restores it to its original size and position.

An application should specify this flag when restoring a minimized window.

10

Sets the show-state based on the state of the program that started the application.

Dim oShell Set oShell = WScript.CreateObject ("WSCript.shell") oShell.run "cmd /K CD C: & Dir" Set oShell = Nothing

SendKeys

The SendKeys method sends one or more keystrokes to the active window (as if typed on the keyboard).

object.SendKeys(string)

You use the SendKeys method to send keystrokes to applications that have no in-built automation interface. Most keyboard characters are represented by a single keystroke while some keyboard characters are made up of combinations of keystrokes (Alt + F4, for example).

To send a single keyboard character, you simply send the character itself as the string argument. For example, to send the letter v, send the string argument "v" . To send a space, send the string " " .

You can also use the SendKeys method to send multiple keystrokes. You do this by creating a compound string argument that represents the sequence of keystrokes by appending each keystroke in the sequence to the one before it. For example, to send the keystrokes x, y, and z, you would send the string argument "xyz" .

The SendKeys method uses some characters as modifiers of other characters. This set of special characters consists of parentheses, brackets, braces, and the following.

Plus sign

"+"

Caret

"^ '

Percent sign

"% '

Tilde

"~"

To send these characters you enclose them inside curly braces "{} '. So if you want to send the plus sign, send the string argument "{+} '.

Square brackets "[]" have no special meaning when used with SendKeys , but you must enclose them within braces to accommodate applications that do give them a special meaning (Dynamic Data Exchange for example).

To send the square bracket characters, send the string argument "{[} ' for the left bracket and "{]}" for the right one. To send curly brace characters, send the string argument "{{} ' for the left brace and "{}} ' for the right one.

Some keystrokes do not generate characters (such as Enter and Tab). Some keystrokes represent actions (such as Backspace and Break). To send these kinds of keystrokes, send the arguments shown in the following table.

Key Argument

Backspace

{BACKSPACE} , {BS} , or {BKSP}

Break

{ BREAK}

Caps Lock

{CAPSLOCK}

Del or Delete

{DELETE} or {DEL}

Down Arrow

{DOWN}

End

{END}

Enter

{ENTER} or ~

Esc

{ESC}

Help

{HELP}

Home

{HOME}

Ins or Insert

{INSERT} or {INS}

Left Arrow

{LEFT}

Num Lock

{NUMLOCK}

Page Down

{PGDN}

Page Up

{PGUP}

Print Screen

{PRTSC}

Right Arrow

{RIGHT}

Scroll Lock

{SCROLLLOCK}

Tab

{TAB}

Up Arrow

{UP}

F1

{F1}

F2

{F2}

F3

{F3}

F4

{F4}

F5

{F5}

F6

{F6}

F7

{F7}

F8

{F8}

F9

{F9}

F10

{F10}

F11

{F11}

F12

{F12}

F13

{F13}

F14

{F14}

F15

{F15}

F16

{F16}

To send keyboard characters that are composed of a regular keystroke in combination with a Shift, Ctrl, or Alt, you will need to create a compound string argument to represent the keystroke combination. You do this by preceding the regular keystroke with one or more of the following special characters.

Key Special Character

Alt

%

Ctrl

^

Shift

+

When used for this purpose, these special characters are not enclosed within a set of braces.

To specify that a combination of Shift, Ctrl, and Alt should be held down while several other keys are pressed, you create a compound string argument with the modified keystrokes enclosed in parentheses. For example, to send the keystroke combination that specifies that the Shift key is held down while:

You can use the SendKeys method to send a pattern of keystrokes that consists of a single keystroke pressed multiple times. This is done by creating a compound string argument that specifies the keystroke you want to repeat, followed by the number of times you want the keystrokes repeated. You do this using a compound string argument of the form {keystroke number} . For example, to send the letter 'V' ten times, you would send the string argument "{V 10} '.

The only keystroke pattern you can send is the kind that is composed of a single keystroke pressed several times. For example, you can send 'V' ten times, but you cannot do the same for ' Ctrl+V '. Note that you cannot send the Print Screen key {PRTSC} to an application.

 

Exec

The Exec method runs an application in a child command shell, which provides access to the StdIn , StdOut , and StdErr streams.

object.Exec(strCommand)

The Exec method returns a WshScriptExec object, which provides status and error information about a script run with Exec along with access to the StdIn , StdOut , and StdErr channels. The Exec method allows the execution of command-line applications only and cannot be used to run remote scripts.

The WshNamed Object

The WshNamed object provides access to the named arguments from the command line.

The Named property of the WshArguments object returns the WshNamed object, which is a collection of arguments that have names. This collection uses the argument name as the index to retrieve individual argument values. There are three ways to access sets of command-line arguments:

Accessing the WshNamed Object

This is accessed by creating an instance of WScript.Named .

Set argsNamed = WScript.Arguments.Named

WshNamed Properties

The WshNamed object has two properties:

Item

The Item property provides access to the items in the WshNamed object.

Object.Item(key)

The Item property returns a string. For collections, it returns an item based on the specified key. When entering the arguments at the command line, you can use spaces in string arguments as long as you enclose the string in quotes. The following line is typed at the command prompt to run the script.

sample.vbs /a:arg1 /b:arg2

If the following code is executed inside the script

WScript.Echo WScript.Arguments.Named.Item("b") WScript.Echo WScript.Arguments.Named.Item("a")

then the following output is produced.

arg2 arg1

Length

The Length property is a read-only integer that you use in scripts when you write in JScript. As such, this is beyond the scope of this book.

WshNamed Methods

The WshNamed object has two methods:

Count

The Count method returns the number of switches in the WshNamed or WshUnnamed objects.

object.Count

The Count method is used to return an integer value. The Count method is intended for VBScript users, and JScript users should use the length property instead.

For x = 0 to WScript.Arguments.Count-1 WScript.Echo WScript.Arguments.Named(x) Next x

Exists

The Exists method indicates whether a specific key value exists in the WshNamed object.

object.Exists(key)

This method returns a Boolean value. It returns True if the requested argument was specified on the command line (otherwise, it returns False ). The following line is typed at the command prompt to run the script.

sample.vbs /a:arg1 /b:arg2

The following code could be used to discover whether the arguments /a , /b , and /c were used.

WScript.Echo WScript.Arguments.Named.Exists("a") WScript.Echo WScript.Arguments.Named.Exists("b") WScript.Echo WScript.Arguments.Named.Exists("c")

The WshUnnamed Object

The WshUnnamed object provides access to the unnamed arguments from the command line. It is a read-only collection that is returned by the Unnamed property of the WshArguments object. All individual argument values are retrieved from this collection using zero-based indexes.

There are three ways to access sets of command-line arguments:

Accessing the WshUnnamed Object

This is accessed by creating an instance of WScript.Arguments.Unnamed .

Set argsUnnamed = WScript.Arguments.Unnamed

WshUnnamed Properties

The WshUnnamed object has two properties:

Both these are similar to that of the WshNamed object and as such don't need to be covered again here.

WshUnnamed Methods

The WshUnnamed object has one method:

This method is similar to that of the WshNamed object and as such doesn't need to be covered again here.

The WshNetwork Object

The WshNetwork object provides access to the shared resources on the network to which the computer is connected.

You will need to create a WshNetwork object when you want to connect to network shares and network printers, disconnect from network shares and network printers, map or remove network shares, or access information about a user on the network.

Accessing the WshNetwork Object

This is accessed by creating an instance of WScript.Network .

Set WshNetwork = WScript.CreateObject("WScript.Network")

WshNetwork Properties

The WshNetwork object has three properties:

ComputerName

The ComputerName property returns the name of the computer system.

object.ComputerName

The ComputerName property contains a string value that indicates the name of the computer system.

 

UserDomain

The UserDomain property returns a user's domain name.

object.UserDomain

The UserDomain property will not work on Windows 98 and Windows Me unless the USERDOMAIN environment variable is set. This variable is not set by default.

 

UserName

The UserName property returns the name of a user.

object.UserName

The UserName property returns the name of a user as a string.

 

WshNetwork Methods

The WshNetwork object makes available the following eight methods:

AddWindowsPrinterConnection

The AddWindowsPrinterConnection method adds a Windows printer connection to your computer system.

Windows NT/2000/XP

object.AddWindowsPrinterConnection( strPrinterPath )

Windows 9x/Me

object.AddWindowsPrinterConnection( strPrinterPath, strDriverName[,strPort] )

Using this method is very similar to using the Printer option on Control Panel to add a printer connection. This method allows you to create a printer connection without the inconvenience of having to direct it to a specific port.

If the connection fails, an error is generated.

Set WshNetwork = WScript.CreateObject("WScript.Network") PrinterPath = "printerserverDefaultPrinter" WshNetwork.AddWindowsPrinterConnection PrinterPath

AddPrinterConnection

The AddPrinterConnection method adds a remote MS-DOS printer connection to your computer system.

object.AddPrinterConnection(strLocalName, strRemoteName[,bUpdateProfile][,strUser][,strPassword])

EnumNetworkDrives

The EnumNetworkDrives method returns the current network drive mapping information.

objDrives = object.EnumNetworkDrives

This method returns a collection which is an array that associates pairs of items-network drive local names and their associated UNC (Universal Naming Convention) names. Even-numbered items in the collection represent local names of logical drives while odd-numbered items represent the associated UNC share names.

The first item in the collection is at index zero ( ).

EnumPrinterConnection

The EnumPrinterConnections method returns the current network printer mapping information.

objPrinters = object.EnumPrinterConnections

The EnumPrinterConnections method returns a collection that consists of an array that associates pairs of items-network printer local names and their associated UNC names. Even-numbered items in the collection represent printer ports while odd-numbered items represent the networked printer UNC names.

The first item in the collection is at index zero ( ).

MapNetworkDrive

The MapNetworkDrive method adds a shared network drive to your computer system.

object.MapNetworkDrive(strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword])

An attempt to map a nonshared network drive will result in an error being generated.

RemoveNetworkDrive

The RemoveNetworkDrive method removes a shared network drive from your computer system.

object.RemoveNetworkDrive(strName, [bForce], [bUpdateProfile])

If the drive has a mapping between a local name (drive letter) and a remote name (UNC name) then strName must be set to the local name. If the network path does not have a local name mapping, then strName must be set to the remote name. The following script removes the network drive "G:" .

Dim WshNetwork Set WshNetwork = WScript.CreateObject("WScript.Network") WshNetwork.RemoveNetworkDrive "G:"

RemovePrinterConnection

The RemovePrinterConnection method removes a shared network printer connection from a computer.

object.RemovePrinterConnection(strName, [bForce], [bUpdateProfile])

The RemovePrinterConnection method will remove both Windows- and MS-DOS-based printer connections.

If the printer was connected using the method AddPrinterConnection , strName must be the printer's local name.

If the printer was connected using the AddWindowsPrinterConnection method or was added manually, then strName must be the printer's UNC name.

SetDefaultPrinter

The SetDefaultPrinter method assigns a remote printer as the default printer.

object.SetDefaultPrinter(strPrinterName)

The SetDefaultPrinter method will fail when using a DOS-based printer connection. Also, you cannot use the SetDefaultPrinter method to determine the name of the currently installed default printer.

The WshEnvironment Object

The WshEnvironment object provides access to the collection of Windows environment variables.

This object is a collection of environment variables that are returned by the WshShell object's Environment property. This collection contains the entire set of environment variables (both those with names and those without).

To retrieve individual environment variables (and their values) from this collection, you would use the environment variable name as the index.

Accessing the WshEnvironment Object

This is accessed by creating an instance of WScript.Environment . The following script returns the number of processors installed on the system running the script.

Set WshShell = WScript.CreateObject("WScript.Shell") Set WshSysEnv = WshShell.Environment("SYSTEM") WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")

WshEnvironment Properties

The WshEnvironment object has two properties:

Item

The Item property exposes a specified item from a collection.

Object.Item(natIndex)

Item is the default property for each collection. For EnumNetworkDrive and EnumPrinterConnections collections, index is an integer, while for the Environment and SpecialFolders collections, index is a string.

WshShell.SpecialFolders.Item (strFolderName) returns "Empty" in VBScript if the requested folder ( strFolderName ) is not available.

 

Length

The Length property is a read-only integer that you use in scripts when you write in JScript. As such, this is beyond the scope of this book.

WshEnvironment Methods

The WshEnvironment object has two methods:

Count

The Count method returns a Long value, which is the number of items in the collection.

object.Count

The Count method returns an integer value. The Count method is intended for VBScript users,and JScript users should use the Length property.

For x = 0 to WScript.Arguments.Count-1 WScript.Echo WScript.Arguments.Named(x) Next x

Remove

The Remove method removes an existing environment variable.

object.Remove(strName)

The Remove method removes environment variables from the following types of environments:

Environment variables removed with the Remove method are not permanently removed and are restored at the end of the current session.

Dim WshShell, WshEnv Set WshShell = WScript.CreateObject("WScript.Shell") Set WshEnv = WshShell.Environment("PROCESS") WshEnv("tVar") = "VBScript is Cool!" WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%tVar%'") WshEnv.Remove "tVar" WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%tVar%'")

The WshSpecialFolders Object

The WshSpecialFolders object provides access to the collection of Windows special folders.

The WshShell object's SpecialFolders property returns the WshSpecialFolders object. This collection contains references to Windows special folders (for example, the Desktop folder and Start Menu folder).

This collection retrieves the paths to special folders using the special folder name as the index. The path of a special folder depends on the user environment. If there are several different users on the same computer, several different sets of special folders will exist on the hard drive.

The following special folders are available:

WshSpecialFolders Properties

The WshSpecialFolders object has one property:

Item

The Item property exposes a specified item from a collection.

Object.Item(natIndex)

Item is the default property for each collection. For EnumNetworkDrive and EnumPrinterConnections collections, index is an integer, while for the Environment and SpecialFolders collections, index is a string.

 

WshSpecialFolders Methods

The WshSpecialFolders object has one method:

Count

The Count method returns the number of switches in the WshNamed or WshUnnamed object.

object.Count

The Count method returns an integer value. The Count method is intended for VBScript users, and JScript users should use the Length property.

The WshShortcut Object

The WshShortcut object allows you to create shortcuts using script.

 

WshShortcut Properties

The WshShortcut object has eight properties:

Arguments

The Arguments property contains the WshArguments object (a collection of arguments). Use a zero-based index to retrieve individual arguments from this collection.

Set objArgs = WScript.Arguments For x = 0 to objArgs.Count - 1 WScript.Echo objArgs(x) Next

Description

The Description property returns a description of a shortcut.

object.Description

The Description property contains a string value describing a shortcut.

 

FullName

The FullName property returns the fully qualified path of the shortcut object's target.

object.FullName

The FullName property contains a read-only string value that gives the fully qualified path to the shortcut's target.

 

Hotkey

The Hotkey property is used to assign a key combination to a shortcut, or identifies the key combination assigned to a shortcut. A hotkey is a combination of keys that starts a shortcut when all associated keys are held down at the same time.

object.Hotkey = strHotkey

The following is the syntax of strHotkey .

[KeyModifier]KeyName

KeyModifier - KeyModifier can be any one of the following: Alt+, Ctrl+, Shift+, Ext+.

Ext+ means 'Extended key.' This has been added in case a new type of Shift key is added to the character set in the future.

KeyName - a z , 9 , F1 F12 ,

The KeyName is not case-sensitive.

 

IconLocation

The IconLocation property is used to assign an icon to a shortcut, or identify the icon assigned to a shortcut.

object.IconLocation = strIconLocation

TargetPath

The TargetPath property gives the path to the shortcut's executable file.

object.TargetPath

This property is for the shortcut's target path only. Any arguments provided must be placed in the Argument 's property.

 

WindowStyle

The WindowStyle property is used to either assign a window style to a shortcut or identify the type of window style used by a shortcut.

object.WindowStyle = intWindowStyle

The WindowStyle property returns an integer.

The following table lists the available settings for intWindowStyle .

InWindowStyle Description

1

Activates and displays a window.

If the window is minimized or maximized, the system restores it to its original size and position.

An application should specify this flag when displaying the window for the first time.

3

Activates the window and displays it as a maximized window.

7

Displays the window as a minimized window.

The active window remains active.

 

WorkingDirectory

The WorkingDirectory property is used to assign a working directory to a shortcut, or to identify the working directory used by a shortcut.

object.WorkingDirectory = strWorkingDirectory

WshShortcut Methods

The WshShortcut object has one method:

Save

The Save method saves a shortcut object to disk.

object.Save

After you have used the CreateShortcut method to create a shortcut object and set the shortcut object's properties, you use the Save method to save the shortcut object to the hard drive. The Save method uses the information in the shortcut object's FullName property to determine where to place the shortcut object on a hard drive.

Shortcuts can only be created to system objects-files, directories, and drives. Shortcuts cannot be created to printer or scheduled tasks.

The WshUrlShortcut Object

The WshUrlShortcut object allows you to create shortcuts to Internet resource using script. It is a child object of the WshShell object. You must use the WshShell method's CreateShortcut to create a WshUrlShortcut object. This file would be saved as a .wsf Windows Script file.

WshShell.CreateShortcut(strDesktop & "URLShortcut.lnk")

WshUrlShortcut Properties

The WshUrlShortcut object has two properties:

FullName

The FullName property returns the fully qualified path of the shortcut object's target.

object.FullName

The FullName property contains a read-only string value that gives the fully qualified path to the shortcut's target. This file would be saved as a .wsf Windows Script file.

 

TargetPath

The TargetPath property gives the path to the shortcut's executable file.

object.TargetPath

This property is for the shortcut's target path only. Any arguments provided must be placed in the Argument 's property. This file would be saved as a .wsf Windows Script file.

 

WshUrlShortcut Methods

The WshUrlShortcut object has one method:

Save

The Save method saves a shortcut object to disk.

object.Save

After you have used the CreateShortcut method to create a shortcut object and set the shortcut object's properties, you use the Save method to save the shortcut object to the hard drive. The Save method uses the information in the shortcut object's FullName property to determine where to place the shortcut object on a hard drive. This file would be saved as a .wsf Windows Script file.

 

Summary

We have covered a lot in this chapter. Here's a recap of the topics we've looked at:

Категории