如何使用C++调用WMI实例的方法

WMI接口对于C++来说十分不友好,包括文档,对于实例对象,通常可以通过WQL查询获得查询对象的实例, 比如:

hr = pSvc->ExecQuery(bstr_t("WQL"), bstr_t("SELECT * FROM Win32_Service"),
                    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
                    NULL,&pEnumerator);

可以获取系统服务对象的集合,通过pEnumerator可以获得所有服务的实例,通过实例通过Get方法获得属性是容易的,对应的sample在网上也很多.但是涉及到通过某个具体的实例调用class的方法,却没有什么sample.看起来微软故意隐藏了这个方面的实现细节.最近终于找到一篇文章描述如何透过WMI实例调用class方法,最根本的地方是要通过实例对象,获取instance class名字,作为IWbemServices::ExecMethod 的第一个参数strOjbectPath.以下代码片段是设置service start type的sample, 一看就明白

 pSvc->ExecQuery(bstr_t("WQL"), bstr_t("SELECT * FROM Win32_Service"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL, &pEnumerator);
while(pEnumerator) {
pEnumerator->Next(WBEM_INFINITE, 1,&pclsObj, &uReturn);
VARIANT vtProp;
pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
if (0 == wcscmp(vtProp.bstrVal, serviceName)) {
break;
}
_SafeRelease(pclsObj);
}
pSvc->GetObject(_bstr_t(L"Win32_Service"), 0, NULL, &pServiceClass, NULL);
pServiceClass->GetMethod(_bstr_t(L"ChangeStartMode"), 0, &pInParams, NULL);
pInParams->SpawnInstance(0, &pInParamsInst);
VARIANT varStartType;
varStartType.vt = VT_BSTR;
varStartType.bstrVal = _bstr_t(L"Automatic");
pInParamsInst->Put(L"StartMode", 0, &varStartType, 0);

// Get the "this" pointer to our object instance so that we
// can call the RenamePrinter method on it
VARIANT var;
hr = pclsObj->Get(L"__RELPATH", 0, &var, NULL, NULL);
if (FAILED(hr))
goto Exit;

pSvc->ExecMethod(var.bstrVal, _bstr_t(L"ChangeStartMode"),
0, NULL, pInParamsInst, &pOutParams, NULL);
VariantClear(&var);


Advertisements
This entry was posted in tech and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s