Programming the WshShell Object
WshShell is a generic name for a powerful object that enables you to query and interact with various aspects of the Windows shell. You can display information to the user, run applications, create shortcuts, work with the Registry, and control Windows' environment variables. The next few sections discuss each of those useful tasks.
Referencing the WshShell Object
WshShell refers to the Shell object exposed via the Automation interface of WScript. Therefore, you must use CreateObject to return this object:
Set objWshShell = WScript.CreateObject("WScript.Shell")
From here, you can use the objWshShell variable to access the object's properties and methods.
Displaying Information to the User
You saw earlier that the WScript object's Echo method is useful for displaying simple text messages to the user. You can gain more control over the displayed message by using the WshShell object's Popup method. This method is similar to the MsgBox function used in Visual Basic and VBA in that it enables you to control both the dialog box title and the buttons displayed, as well as to determine which of those buttons the user pressed. Here's the syntax:
WshShell.Popup(strText, [nSecondsToWait], [strTitle], [intType])
WshShell |
The WshShell object. |
strText |
The message you want to display in the dialog box. You can enter a string up to 1,024 characters long. |
nSecondsToWait |
The maximum number of seconds the dialog box will be displayed. |
strTitle |
The text that appears in the dialog box title bar. If you omit this value, Windows Script Host appears in the title bar. |
intType |
A number or constant that specifies, among other things, the command buttons that appear in the dialog box (see the next section). The default value is 0. |
For example, the following statements display the dialog box shown in Figure 12.2:
Set objWshShell = WScript.CreateObject("WScript.Shell") objWshShell.Popup "Couldn't find Memo.doc!", , "Warning"
Figure 12.2 A simple message dialog box produced by the Popup method.
Setting the Style of the Message
The default Popup dialog box displays only an OK button. You can include other buttons and icons in the dialog box by using different values for the intType parameter. Table 12.1 lists the available options.
Table 12.1. The Popup Method's intType Parameter Options
VBScript Constant |
Value |
Description |
Buttons |
||
vbOKOnly |
0 |
Displays only an OK button. This is the default. |
vbOKCancel |
1 |
Displays the OK and Cancel buttons. |
vbAbortRetryIgnore |
2 |
Displays the Abort, Retry, and Ignore buttons. |
vbYesNoCancel |
3 |
Displays the Yes, No, and Cancel buttons. |
vbYesNo |
4 |
Displays the Yes and No buttons. |
vbRetryCancel |
5 |
Displays the Retry and Cancel buttons. |
Icons |
||
vbCritical |
16 |
Displays the Critical Message icon. |
vbQuestion |
32 |
Displays the Warning Query icon. |
vbExclamation |
48 |
Displays the Warning Message icon. |
vbInformation |
64 |
Displays the Information Message icon. |
Default Buttons |
||
vbDefaultButton1 |
0 |
The first button is the default (that is, the button selected when the user presses Enter). |
vbDefaultButton2 |
256 |
The second button is the default. |
vbDefaultButton3 |
512 |
The third button is the default. |
You derive the intType argument in one of two ways:
- By adding the values for each option
- By using the VBScript constants separated by plus signs (+)
The script in Listing 12.4 shows an example and Figure 12.3 shows the resulting dialog box.
Figure 12.3 The dialog box that's displayed when you run the script.
Listing 12.4. A VBScript Example That Uses the Popup Method to Display the Dialog Box Shown in Figure 12.3
' First, set up the message ' strText = "Are you sure you want to copy" & Chr(13) strText = strText & "the selected files to drive A?" strTitle = "Copy Files" intType = vbYesNoCancel + vbQuestion + vbDefaultButton2 ' ' Now display it ' Set objWshShell = WScript.CreateObject("WScript.Shell") intResult = objWshShell.Popup(strText, ,strTitle, intType)
Here, three variables—strText, strTitle, and intType—store the values for the Popup method's strText, strTitle, and intType arguments, respectively. In particular, the following statement derives the intType argument:
intType = vbYesNoCancel + vbQuestion + vbDefaultButton2
You also could derive the intType argument by adding up the values that these constants represent (3, 32, and 256, respectively), but the script becomes less readable that way.
Getting Return Values from the Message Dialog Box
A dialog box that displays only an OK button is straightforward. The user either clicks OK or presses Enter to remove the dialog from the screen. The multibutton styles are a little different, however; the user has a choice of buttons to select, and your script should have a way to find out which button the user chose, which enables it to decide what to do next, based on the user's selection. You do this by storing the Popup method's return value in a variable. Table 12.2 lists the seven possible return values.
Table 12.2. The Popup Method's Return Values
VBScript Constant |
Value |
Button Selected |
vbOK |
1 |
OK |
vbCancel |
2 |
Cancel |
vbAbort |
3 |
Abort |
vbRetry |
4 |
Retry |
vbIgnore |
5 |
Ignore |
vbYes |
6 |
Yes |
vbNo |
7 |
No |
To process the return value, you can use an If...Then...Else or Select Case structure to test for the appropriate values. For example, the script shown earlier used a variable called intResult to store the return value of the Popup method. Listing 12.5 shows a revised version of the script that uses a VBScript Select Case statement to test for the three possible return values.
Listing 12.5. A Script That Uses a Select Case Statement to Process the Popup Method's Return Value
' First, set up the message ' strText = "Are you sure you want to copy" & Chr(13) strText = strText & "the selected files to drive A?" strTitle = "Copy Files" intType = vbYesNoCancel + vbQuestion + vbDefaultButton2 ' ' Now display it ' Set objWshShell = WScript.CreateObject("WScript.Shell") intResult = objWshShell.Popup(strText, ,strTitle, intType) ' ' Process the result ' Select Case intResult Case vbYes WScript.Echo "You clicked ""Yes""!" Case vbNo WScript.Echo "You clicked ""No""!" Case vbCancel WScript.Echo "You clicked ""Cancel""!" End Select
Running Applications
When you need your script to launch another application, use the Run method:
WshShell.Run strCommand, [intWindowStyle], [bWaitOnReturn]
WshShell |
The WshShell object. |
|
strCommand |
The name of the file that starts the application. Unless the file is in the Windows folder, you should include the drive and folder to make sure that the script can find the file. |
|
intWindowStyle |
A constant or number that specifies how the application window will appear: |
|
intWindowStyle |
Window Appearance |
|
0 |
Hidden |
|
1 |
Normal size with focus |
|
2 |
Minimized with focus (this is the default) |
|
3 |
Maximized with focus |
|
4 |
Normal without focus |
|
6 |
Minimized without focus |
|
bWaitOnReturn |
A logical value that determines whether the application runs asynchronously. If this value is True, the script halts execution until the user exits the launched application; if this value is False, the script continues running after it has launched the application. |
Here's an example:
Set objWshShell = WScript.CreateObject("WScript.Shell") objWshShell.Run "Control.exe Inetcpl.cpl", 1, True
This Run method launches Control Panel's Internet Properties dialog box.
Working with Shortcuts
The Windows Script Host enables your scripts to create and modify shortcut files. When writing scripts for other users, you might want to take advantage of this capability to display shortcuts for new network shares, Internet sites, instruction files, and so on.
Creating a Shortcut
To create a shortcut, use the CreateShortcut method:
WshShell.CreateShortcut(strPathname)
WshShell |
The WshShell object. |
strPathname |
The full path and filename of the shortcut file you want to create. Use the .lnk extension for a file system (program, document, folder, and so on) shortcut; use the .url extension for an Internet shortcut. |
The following example creates and saves a shortcut on a user's desktop:
Set WshShell = objWScript.CreateObject("WScript.Shell") Set objShortcut = objWshShell.CreateShortcut("C:\Users\Paul\Desktop\test.lnk") objShortcut.Save
Programming the WshShortcut Object
The CreateShortcut method returns a WshShortcut object. You can use this object to manipulate various properties and methods associated with shortcut files.
This object contains the following properties:
-
Arguments—Returns or sets a string that specifies the arguments used when launching the shortcut. For example, suppose that the shortcut's target is the following:
C:\Windows\Notepad.exe C:\Boot.ini
In other words, this shortcut launches Notepad and loads the Boot.ini file. In this case, the Arguments property would return the following string:C:\Boot.ini
- Description—Returns or sets a string description of the shortcut.
- FullName—Returns the full path and filename of the shortcut's target. This will be the same as the strPathname value used in the CreateShortcut method.
-
Hotkey—Returns or sets the hotkey associated with the shortcut. To set this value, use the following syntax:
WshShortcut.Hotkey = strHotKey
WshShortcut
The WshShortcut object.
strHotKey
A string value of the form Modifier+Keyname, where Modifier is any combination of Alt, Ctrl, and Shift, and Keyname is one of A through Z or 0 through 12.
objShortcut.Hotkey = "Ctrl+Alt+7"
-
IconLocation—Returns or sets the icon used to display the shortcut. To set this value, use the following syntax:
WshShortcut.IconLocation = strIconLocation
WshShortcut
The WshShortcut object.
strIconLocation
A string value of the form Path,Index, where Path is the full pathname of the icon file and Index is the position of the icon within the file (where the first icon is 0).
objShortcut.IconLocation = "C:\Windows\System32\Shell32.dll,21"
- TargetPath—Returns or sets the path of the shortcut's target.
- WindowStyle—Returns or sets the window style used by the shortcut's target. Use the same values outlined earlier for the Run method's intWindowStyle argument.
- WorkingDirectory—Returns or sets the path of the shortcut's working directory.
The WshShortcut object also supports two methods:
- Save—Saves the shortcut file to disk.
-
Resolve—Uses the shortcut's TargetPath property to look up the target file. Here's the syntax:
WshShortcut.Resolve = intFlag
WshShortcut
The WshShortcut object.
intFlag
Determines what happens of the target file is not found:
intFlag
What Happens
1
Nothing
2
Windows continues to search subfolders for the target file
4
Updates the TargetPath property if the target file is found in a new location
Listing 12.6 shows a complete example of a script that creates a shortcut.
Listing 12.6. A Script That Creates a Shortcut File
Set objWshShell = WScript.CreateObject("WScript.Shell") Set objShortcut = objWshShell.CreateShortcut("C:\Users\Paul\Desktop\Edit BOOT.INI.lnk") With objShortcut .TargetPath = "C:\Windows\Notepad.exe " .Arguments = "C:\Boot.ini" .WorkingDirectory = "C:\" .Description = "Opens BOOT.INI in Notepad" .Hotkey = "Ctrl+Alt+7" .IconLocation = "C:\Windows\System32\Shell32.dll,21" .WindowStyle = 3 .Save End With
Working with Registry Entries
You've seen throughout this book that the Registry is one the most crucial data structures in Windows. However, the Registry isn't a tool that only Windows yields. Most 32-bit applications make use of the Registry as a place to store setup options, customization values the user selected, and much more. Interestingly, your scripts can get in on the act as well. Not only can your scripts read the current value of any Registry setting, but they can also use the Registry as a storage area. This enables you to keep track of user settings, recently used files, and any other configuration data that you'd like to save between sessions. This section shows you how to use the WshShell object to manipulate the Registry from within your scripts.
Reading Settings from the Registry
To read any value from the Registry, use the WshShell object's RegRead method:
WshShell.RegRead(strName)
WshShell |
The WshShell object. |
|
strName |
The name of the Registry value or key that you want to read. If strName ends with a backslash (\), RegRead returns the default value for the key; otherwise, RegRead returns the data stored in the value. Note, too, that strName must begin with one of the following root key names: |
|
Short Name |
Long Name |
|
HKCR |
HKEY_CLASSES_ROOT |
|
HKCU |
HKEY_CURRENT_USER |
|
Short Name |
Long Name |
|
HKLM |
HKEY_LOCAL_MACHINE |
|
N/A |
HKEY_USERS |
|
N/A |
HKEY_CURRENT_CONFIG |
The script in Listing 12.7 displays the name of the registered owner of this copy of Windows XP.
Listing 12.7. A Script That Reads the RegisteredOwner Setting from the Registry
Set objWshShell = WScript.CreateObject("WScript.Shell") strSetting = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOwner" strRegisteredUser = objWshShell.RegRead(strSetting) WScript.Echo strRegisteredUser
Storing Settings in the Registry
To store a setting in the Registry, use the WshShell object's RegWrite method:
WshShell.RegWrite strName, anyValue [, strType]
WshShell |
The WshShell object. |
strName |
The name of the Registry value or key that you want to set. If strName ends with a backslash (\), RegWrite sets the default value for the key; otherwise, RegWrite sets the data for the value. strName must begin with one of the root key names detailed in the RegRead method. |
anyValue |
The value to be stored. |
strType |
The data type of the value, which must be one of the following: REG_SZ (the default), REG_EXPAND_SZ, REG_DWORD, or REG_BINARY. |
The following statements create a new key named ScriptSettings in the HKEY_CURRENT_USER root:
Set objWshShell = WScript.CreateObject("WScript.Shell") objWshShell.RegWrite "HKCU\ScriptSettings\", ""
The following statements create a new value named NumberOfReboots in the HKEY_CURRENT_USER\ScriptSettings key, and set this value to 1:
Set objWshShell = WScript.CreateObject("WScript.Shell") objWshShell.RegWrite "HKCU\ScriptSettings\NumberOfReboots", 1, "REG_DWORD"
Deleting Settings from the Registry
If you no longer need to track a particular key or value setting, use the RegDelete method to remove the setting from the Registry:
WshShell.RegDelete(strName)
WshShell |
The WshShell object. |
strName |
The name of the Registry value or key that you want to delete. If strName ends with a backslash (\), RegDelete deletes the key; otherwise, RegDelete deletes the value. strName must begin with one of the root key names detailed in the RegRead method. |
To delete the NumberOfReboots value used in the previous example, you would use the following statements:
Set objWshShell = WScript.CreateObject("WScript.Shell") objWshShell.RegDelete "HKCU\ScriptSettings\NumberOfReboots"
Working with Environment Variables
Windows Vista keeps track of a number of environment variables that hold data such as the location of the Windows folder, the location of the temporary files folder, the command path, the primary drive, and much more. Why would you need such data? One example would be for accessing files or folders within the main Windows folder. Rather than guessing that this folder is C:\Windows, it would be much easier to just query the %SystemRoot% environment variable. Similarly, if you have a script that accesses files in a user's My Documents folder, hard-coding the username in the file path is inconvenient because it means creating custom scripts for every possible user. Instead, it would be much easier to create just a single script that references the %UserProfile% environment variable. This section shows you how to read environment variable data within your scripts.
The defined environment variables are stored in the Environment collection, which is a property of the WshShell object. Windows Vista environment variables are stored in the "Process" environment, so you reference this collection as follows:
WshShell.Environment("Process")
Listing 12.8 shows a script that runs through this collection, adds each variable to a string, and then displays the string.
Listing 12.8. A Script That Displays the System's Environment Variables
Set objWshShell = WScript.CreateObject("WScript.Shell") ' ' Run through the environment variables ' strVariables = "" For Each objEnvVar In objWshShell.Environment("Process") strVariables = strVariables & objEnvVar & Chr(13) Next WScript.Echo strVariables
Figure 12.4 shows the dialog box that appears (your mileage may vary).
Figure 12.4 A complete inventory of a system's environment variables.
If you want to use the value of a particular environment variable, use the following syntax:
WshShell.Environment("Process")("strName")
WshShell |
The WshShell object |
strName |
The name of the environment variable |
Listing 12.9 shows a revised version of the script from Listing 12.6 to create a shortcut. In this version, the Environment collection is used to return the value of the %UserProfile% variable, which is used to contrast the path to the current user's Desktop folder.
Listing 12.9. A Script That Creates a Shortcut File Using an Environment Variable
Set objWshShell = WScript.CreateObject("WScript.Shell") strUserProfile = objWshShell.Environment("Process")("UserProfile") Set objShortcut = objWshShell.CreateShortcut(strUserProfile & _ "\Desktop\Edit BOOT.INI.lnk") With objShortcut .TargetPath = "C:\Windows\Notepad.exe " .Arguments = "C:\Boot.ini" .WorkingDirectory = "C:\" .Description = "Opens BOOT.INI in Notepad" .Hotkey = "Ctrl+Alt+7" .IconLocation = "C:\Windows\System32\Shell32.dll,21" .WindowStyle = 3 .Save End With