I've noticed that some Windows Script Host (WSH) scripts use WScript.CreateObject, whereas other scripts use CreateObject (no WScript.). Can you explain the difference between the two and when to use each one?
Perhaps the easiest way to understand the similarities and differences between WSH's WScript.CreateObject method and VBScript's CreateObject function is by comparing their signatures. In short, a signature is just a fancy phrase for the notation used to define a method or function. The definition includes the method's or function's name, mandatory and optional parameters, and return value. The online WSH documentation (http://msdn.microsoft.com/library/en-us/script56/html/wsmthcreateobject.asp) defines the signature for the WScript.CreateObject method as
The online VBScript documentation (http://msdn.microsoft.com/library/en-us/script56/html/vsfctcreateobject.asp) defines the signature for the CreateObject function as
If you compare the two signatures, you'll notice that the CreateObject method and CreateObject function have one mandatory parameter and one optional parameter. (The parameters in square brackets are optional.) Let's briefly examine the role of the first parameter, which is mandatory.
Although the CreateObject method and the CreateObject function use noticeably different names for the first parameter (i.e., strProgID and servername.typename, respectively), the parameters' purpose is functionally identical. The mandatory parameter provides the programmatic identifier (ProgID) of the object you want to create. As such, the two statements that Listing 3 shows are functionally equivalent. Both statements create an instance of the Scripting Runtime's FileSystemObject object and assign it to a variable (i.e., objFSO1 or objFSO2).
The functional difference between the CreateObject method and CreateObject function lies in their optional second parameters (strPrefix and location, respectively). The CreateObject method's second parameter supports capturing events from automation objects that fire events. The CreateObject function's second parameter supports creating objects on remote computers.
In scripts in which you're only using the mandatory parameter, I recommend that you use VBScript's CreateObject function instead of the WScript.CreateObject method. The VBScript function requires less typing and makes your scripts slightly more readable and portable if you dabble in other script host environments. If you're writing scripts that capture events or create objects on remote computers, the choice of whether to use the CreateObject method or CreateObject function becomes obvious. To learn more about how to choose the correct method, function, or object when writing code, see the following topics in the Microsoft Windows 2000 Scripting Guide:
- "Choosing a Method for Binding to an Automation Object"
- "Using COM Objects"