Home > Articles > Operating Systems, Server > Microsoft Servers

This chapter is from the book

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

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

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.

    For example, the following statement sets the hotkey to Ctrl+Alt+7:
    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).

    Here's an example:
    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

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020