jacouh
jacouh

Reputation: 8741

WScript.GetObject() does not work, but GetObject() does

When using VBScript to get processes list on Windows 7 Pro, this script, named as getobject.vbs, is used:

Dim objWMIService

'
' case 1: this works:
'
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
WScript.Echo "GetObject() worked."

'
' case 2: this does not work:
'
Set objWMIService = WScript.GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
WScript.Echo "WScript.GetObject() does not work. So this line never runs."

'
' ...
'
Set objWMIService = Nothing

In case 1, GetObject() works well.

But in case 2, when WScript.GetObject() is used, this error occurs:

enter image description here

GetObject() is a method of WScript, please see Microsoft ref.. Why cannot one call it by the complete reference in the form of WScript.GetObject()?

As a comparision, the both calls worked:

Dim xobj

Set xobj = CreateObject("Excel.Application")

Set xobj = WScript.CreateObject("Excel.Application")

Upvotes: 1

Views: 2876

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

There is a GetObject function of the VBScript language and a GetObject method of the WScript object. They are not the same, their prototypes and usage/pragmatics differ.

Update wrt comment:

Read Eric Lippert's article to understand why there are host- and language-provided variants of similar functions.

My rule of thump: Use the language version of Create/GetObject(), except when you need the extras (e.g. events) provided by the host application.

Upvotes: 4

Related Questions