Previous Page
Next Page

Using the Default WMI Moniker Step-by-Step Exercises

In this section, you will practice using the default WMI moniker. To do this, you write a cute little script that enumerates all the programs listed in the Add/Remove Programs dialog box, available from Control Panel.

1.
Open Notepad or your favorite script editor.

2.
On the first line, type Option Explicit to ensure you declare all variables used in the script.

3.
Declare the following variables: objWMIService, colItems, and objItem. Add comments following each declaration to specify what each variable is used for.

4.
Set objWMIService equal to what comes back from the GetObject method when used in conjunction with the WMI moniker. Your code will look like the following:

Set objWMIService = GetObject("winmgmts:\\")

5.
Set colItems equal to what comes back from issuing the WQL statement "Select * from WIN32_Product" as you use the ExecQuery method. Your code will look like the following:

Set colItems = objWMIService.ExecQuery("SELECT * FROM WIN32_Product")

6.
Use a For Each...Next loop to iterate through colItems as you look for the following properties of the AddRemovePrograms object: DisplayName, Publisher, and Version. Use the variable objItem to assist you in iterating through the collection. Make sure you close out the For Each...Next loop with the Next command. Your code could will look like the following:

For Each objItem In colItems
  WScript.Echo "DisplayName: " & objItem.Name
  WScript.Echo "Publisher: " & objItem.Vendor
  WScript.Echo "Version: " & objItem.Version
  WScript.Echo
Next

7.
Save your file as YourNameDefaultMoniker.vbs.

8.
Make sure you run this program in CScript by going to a command prompt and typing cscript pathtoyourfile\yourNameDefaultMoniker.vbs. (More than likely, you have a lot of programs in Add/Remove Programs. If you run the program by double-clicking it, and it runs under WScript, you will have numerous pop-up dialog boxes to close unless you open Task Manager and kill the WScript.exe process.) Depending on how many programs you have installed, it will take several minutes for your script to run.

9.
EXTRA CREDIT: Add a message to the beginning of your script letting the user know the script is beginning. Also add a message letting the user know when the script is finished. Then tell the user how long the script ran. Compare your results with \My Documents\Microsoft Press\VBScriptSBS\StepByStep\DefaultMonikerExtra.vbs.


Previous Page
Next Page