Share via


Creating an Object Reference

Microsoft® Windows® 2000 Scripting Guide

With Automation, you do not work directly with an object itself. Instead, you create a reference to the object by using GetObject or CreateObject and then assign this reference to a variable. After the reference has been created, you can access the methods and properties of the object by using the variable rather than the object itself.

In the script in Listing 2.2, the GetObject method is used to assign the WMI SWbemServices object to the variable objWMIService. After the assignment has been made, all the properties of the SWbemServices object can be accessed through objWMIService. For example, in line 2 of the script, the Get method is used to retrieve the properties for drive C.

Anytime you create an object reference, you must use the Set keyword when assigning the reference to a variable. For example, the following line of code will result in a run-time error:

objWMIService = GetObject("winmgmts:")

To create the object reference, you must use the Set keyword like this:

Set objWMIService = GetObject("winmgmts:")

Set is a special VBScript statement that is used only when creating an object reference. If you use Set for other purposes, such as assigning a value to a variable, a run-time error will occur. For example, this line of code will fail because no object named 5 can be found on the computer:

Set x = 5