Do you have a scripting-related question or problem? You can send your question or problem to [email protected]
Q: I'm running a Windows Script Host (WSH) script that depends on a custom object to work. How can I determine whether this object is available on a PC before I use WSH's CreateObject method to create an instance of it?
A:There are several ways to determine whether a custom object is available. One of the quickest methods is to use a piece of information you already know: the object's programmatic identifier (ProgID). For example, the ProgID for Microsoft Word's Application object (i.e., Word's root object) is Word.Application.
When a COM object is registered on a PC, the Windows OS creates a set of registry entries to help applications that use the object find its location. The OS uses the object's ProgID as the name of a key in the registry's HKEY_CLASSES_ROOT subtree. Each ProgID key has an associated class identifier (CLSID) subkey, whose default value is the object's globally unique identifier (GUID). For example, the GUID for Word's Application object is in the HKEY_CLASSES_ROOT\Word.Application\CLSID subkey.
The IsProgId function, which Listing 1 shows, uses the WshShell object's RegRead method to check the specified object's CLSID subkey for a GUID. When RegRead retrieves a GUID, the function returns a value of True to indicate that the object exists. If the GUID is missing or the CLSID subkey doesn't exist, the Err object returns the error number 0x80070002, causing the function to return a value of False.
Note that the IsProgId function looks for a value in the CLSID subkey rather than the ProgID key to avoid inaccurate results. For a COM object to work, its CLSID subkey must have a value. In contrast, ProgID keys don't need a default value (although they typically have one). If RegRead encounters a ProgID key without a default value, an error would occur and the IsProgId function would return a value of False. In other words, the function would report that the object doesn't exist. This result would be incorrect because the object does exist--it just doesn't have a default value. Checking the CLSID subkey rather than the ProgID key avoids this problem.
To use the IsProgId function, you need to call it in your script. For example, if you want to determine whether Word's Application object is available on a PC, you might use a call such as
WScript.Echo _ IsProgId("Word.Application")