Verifying Object References

Microsoft® Windows® 2000 Scripting Guide

The IsObject function allows you to verify that you were able to obtain an object reference. If the GetObject or CreateObject call succeeds, IsObject will return True (-1). If the GetObject or CreateObject call fails, IsObject will return False (0). For example, the following code uses CreateObject to try to obtain an object reference (assigned to the variable TestObject) to a nonexistent object. Because the object call fails, TestObject is not assigned an object reference, and IsObject returns 0.

On Error Resume Next
Set TestObject = CreateObject("Fake.Object")
Wscript.Echo IsObject(TestObject)

Unfortunately, VBScript assumes that once an object reference has been established, that reference will remain valid for the lifetime of the script. That is generally not a problem, particularly for ADSI and WMI, which are unlikely to disappear while the script is running.

The same cannot be said for other Automation objects, however. For example, consider the following script, which starts an instance of Microsoft Word, immediately stops that instance, and then uses IsObject to test whether the object reference is still valid:

Set TestObject = CreateObject("Word.Application")
TestObject.Quit
Wscript.Echo IsObject(TestObject)

When the script runs, IsObject reports that TestObject is still an object because TestObject is still an object reference; it just no longer points to a running instance of Microsoft Word.

There are two ways to work around this problem. One approach is to use WMI to verify that the process (in this case, Winword.exe) is still running. Although this method will work, it requires you to repeatedly query the set of running processes on the computer, something that will slow your script. In addition, matters can get complicated if multiple instances of Winword.exe are running because there is no straightforward method for identifying the instance of Winword.exe that you created and that your object reference refers to. To avoid possible problems (such as a script that inadvertently deletes text from the wrong Word document), your script should use the same instance of Winword.exe all the way through.

A better approach is to add eventing to your script. With this approach, your script can receive notification when specified events occur with your Automation object. For example, should Word quit unexpectedly, notice can be sent to your script that the Word object is no longer available. Your script can then take the appropriate action.

For more information about adding eventing to a script, see "Creating Enterprise Scripts" in this book.