Using WMI to Extract Management Information

Environment: VC6, WMI SDK

This week I gained a little experience of WMI using, so I would share it with you.
The attached application is WMI client which can connect to WMI management servers
and performs some activities:

  • enumerating all instances of most populated CIMV2 classes,
  • displaying their properties (only BSTR types),
  • executing methods (for Win32_Process and Win32_OperatingSystem classes only), and
  • connecting to any computer and performing WMI login for different users and passwords.

In order to execute class object methods press the right button on selected instance
and choose from pop up menu the method you want to execute.

REMEMBER the Win32_OperatingSystem methods are booting the PC, so save all your works before trying it.

Take a look at the function implementation in AcWMI.h and its cpp file. These functions manipulate the WMI interfaces and supply the following functionality.
I will be glad if youll find some problems or bugs in this implementation and report to me. If you have any suggestion or question please refer to me.

Connecting to WMI namespace services (using password and username is not required for local machine).



///////////////////////////////////////////////////////////////////////
//1) Connecting to WMI namespace services (using password and username
// is not required for local machine). This function returns IWbemLocator,
// IWbemServices interface pointers and the user error description.
///////////////////////////////////////////////////////////////////////

HRESULT ConnectServerWMI ( OUT IWbemLocator** ppiWmiLoc ,
OUT IWbemServices** ppiWmiServ ,
const CString csNamespace ,
const CString csUsername ,
const CString csPassword ,
CString& csErrRef )
{
if (NULL == ppiWmiServ || NULL == ppiWmiLoc) {
csErrRef = _T(“Invalid argument”);
return E_INVALIDARG;
}

HRESULT hres;
hres = CoCreateInstance ( CLSID_WbemLocator, 0,
CLSCTX_INPROC_SERVER, IID_IWbemLocator,
(LPVOID *) ppiWmiLoc );

if (FAILED(hres)) {
csErrRef = _T(“Failed to create IWbemLocator object.”);
return hres;
}

CComBSTR bstrNamespace(csNamespace);

if (csPassword.IsEmpty() || csUsername.IsEmpty())
{
hres = (*ppiWmiLoc)->ConnectServer(bstrNamespace, NULL, NULL,
0, NULL, 0, 0, ppiWmiServ );
}
else
{
// connect server using password and username
CComBSTR bstrUsername(csUsername), bstrPassword(csPassword);

hres = (*ppiWmiLoc)->ConnectServer(bstrNamespace, bstrUsername,
bstrPassword, 0, NULL, 0, 0,
ppiWmiServ );
}

if (FAILED(hres))
{
(*ppiWmiLoc)->Release();

csErrRef = _T(“Failed to connect server.”);
return hres;
}

hres = CoSetProxyBlanket( *ppiWmiServ ,
RPC_C_AUTHN_WINNT ,
RPC_C_AUTHZ_NONE ,
NULL,
RPC_C_AUTHN_LEVEL_CALL ,
RPC_C_IMP_LEVEL_IMPERSONATE ,
NULL,
EOAC_NONE);

if(FAILED(hres))
{
(*ppiWmiLoc)->Release();
(*ppiWmiServ)->Release();

csErrRef = _T(“Can not set proxy blank.”);
return hres;
}

return hres;
}

///////////////////////////////////////////////////////////////////////
//2) Enumerating of all similar service instances in OS is doing by
// EnumInstancesWMI function. This function returns IEnumWbemClassObject
// interface.
///////////////////////////////////////////////////////////////////////

HRESULT EnumInstancesWMI ( IN IWbemServices* piWmiServ ,
OUT IEnumWbemClassObject** ppiWmiEnum ,
const CString& csInstName, CString& csErrRef )
{
if (NULL == piWmiServ || NULL == ppiWmiEnum)
{
csErrRef = _T(“Invalid argument”);
return E_INVALIDARG;
}

HRESULT hres;
CComBSTR bstrObjectName(csInstName);

hres = piWmiServ->CreateInstanceEnum( bstrObjectName ,
WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY ,
NULL ,
ppiWmiEnum);
if (FAILED(hres))
{
csErrRef.Format(“Could not enumerate %s instances.”, csInstName);
return hres;
}
return hres;
}


///////////////////////////////////////////////////////////////////////
//3) Error description is provided by IWbemStatusCodeText interface
// which implemented in my GetLastErrorWMI function. This function
// returns error description by HRESULT argument.
///////////////////////////////////////////////////////////////////////

HRESULT GetLastErrorWMI (CString& csErrRef, HRESULT hresErr)
{
IWbemStatusCodeText * pStatus = NULL;

HRESULT hres = CoCreateInstance(CLSID_WbemStatusCodeText, 0, CLSCTX_INPROC_SERVER,
IID_IWbemStatusCodeText, (LPVOID *) &pStatus);

if(S_OK == hres)
{
CComBSTR bstrError;
hres = pStatus->GetErrorCodeText(hresErr, 0, 0, &bstrError);

if(S_OK != hres)
bstrError = SysAllocString(L”Get last error failed”);

USES_CONVERSION;
csErrRef = OLE2T(bstrError);

pStatus->Release();
}

return hres;
}

///////////////////////////////////////////////////////////////////////
//4) Enumerating of all property names of instance is doing by
// EnumInstPropNameWMI function. This function is returning string array
// of all properties.
///////////////////////////////////////////////////////////////////////

HRESULT EnumInstPropNameWMI ( IN IWbemClassObject* piappObj,
OUT LPSAFEARRAY* ppsarProp )
{
if (NULL == ppsarProp || NULL == piappObj)
return E_INVALIDARG;

// GetNames methods will create SAFEARRAY,
// but on entry this parameter must point to NULL

if (NULL != *ppsarProp)
{
SafeArrayDestroy(*ppsarProp);
delete *ppsarProp;
*ppsarProp = NULL;

if (NULL == ppsarProp)
return E_INVALIDARG;
}

HRESULT hres;
hres = piappObj->GetNames( NULL,
WBEM_FLAG_ALWAYS | WBEM_FLAG_NONSYSTEM_ONLY,
NULL,
ppsarProp);
return hres;
}


///////////////////////////////////////////////////////////////////////
//5) Another enumerating function enumerates all property names of
// instance in SAFEARRAY type. The SAFEARRAY pointer should be NULL
// at receiving time.
///////////////////////////////////////////////////////////////////////

HRESULT EnumInstPropNameWMI ( IN IWbemClassObject* piappObj,
OUT CStringArray& psarPropRef )
{
HRESULT hres;
SAFEARRAY* pSafeArrProp = NULL;

psarPropRef.RemoveAll();

hres = EnumInstPropNameWMI(piappObj, &pSafeArrProp );

if (WBEM_S_NO_ERROR != hres)
return hres;

long lLower, lUpper;
SafeArrayGetLBound(pSafeArrProp , 1, &lLower);
SafeArrayGetUBound(pSafeArrProp , 1, &lUpper);

for (long i = lLower; i <= lUpper; ++i)
{
CComBSTR bstrPropName;

if (S_OK != (hres = SafeArrayGetElement(pSafeArrProp, &i, &bstrPropName)) )
{
if (NULL != pSafeArrProp)
SafeArrayDestroy(pSafeArrProp);
return hres;
}

USES_CONVERSION;
psarPropRef.SetAtGrow(psarPropRef.GetSize(), OLE2T(bstrPropName));
}

if (NULL != pSafeArrProp)
SafeArrayDestroy(pSafeArrProp);

return hres;
}


///////////////////////////////////////////////////////////////////////
//6) Executing instance method I do through ExecMethodWMI.
// The user has to take care to the property name array,
// in – argument VARIANT array and size of in – arguments he
// want to receive into object method.
// See the void CWMI_TestDlg::ExecMethod (UINT nID) implementation;
// there I fill these arguments for Win32_Process and
// Win32_OperatingSystem classes.
///////////////////////////////////////////////////////////////////////

HRESULT ExecMethodWMI ( IN IWbemServices* piWmiServ,
const CString& csMethodName,
const CString& csClassName,
const CString& csClassPath,
const CString& csObjectPath,
const CStringArray* csarrPropNames /*=NULL*/,
VARIANT *arrVarInArg/*=NULL*/, const int size_t/*=0*/)
{
// sanity checks
if (NULL == piWmiServ)
return E_INVALIDARG;

if (( NULL != csarrPropNames && NULL == arrVarInArg) ||
( NULL == csarrPropNames && NULL != arrVarInArg) )
return E_INVALIDARG;

if (NULL != csarrPropNames)
{
if(size_t != csarrPropNames->GetSize())
return E_INVALIDARG;
}

IWbemClassObject* pClassObj = NULL;
IWbemClassObject* pOutParam = NULL;
IWbemClassObject* pInParam = NULL;

IWbemClassObject* pInClass = NULL;
IWbemClassObject* pOutClass = NULL;

CComBSTR bstrMethodName ( csMethodName);
CComBSTR bstrClassName ( csClassName );
CComBSTR bstrClassPath ( csClassPath );
CComBSTR bstrObjectPath ( csObjectPath);

HRESULT hres;
hres = piWmiServ->GetObject(bstrClassName, 0, NULL, &pClassObj, NULL);

if (WBEM_S_NO_ERROR == hres)
{
// get the input-argument class object and create an instance.
// pInClass == NULL indicates that no input parameters needed.

hres = pClassObj->GetMethod(bstrMethodName, 0, &pInClass, NULL);

if (WBEM_S_NO_ERROR == hres)
{
if( NULL != pInClass)
{
// create instance copy
if(WBEM_S_NO_ERROR == (hres=pInClass->SpawnInstance(0, &pInParam)) )
{
// set each property
for (long i = 0; i < size_t; ++i)
{
CComBSTR bstrPropName(csarrPropNames->GetAt(i));
hres = pInParam->Put(bstrPropName, 0, &arrVarInArg[i], 0);

// DUF!!! Put failed, check the properties and their types
if (WBEM_S_NO_ERROR != hres)
break;
}
}
}
// finally call the method
if (WBEM_S_NO_ERROR == hres)
hres = piWmiServ->ExecMethod(bstrObjectPath, bstrMethodName, 0, NULL, pInParam, &pOutParam, NULL);
}
}

// free all resources
if (NULL != pOutParam)
{
// but first we get the output parameters here
CComBSTR bstrClassObj;
hres = pOutParam->GetObjectText(0, &(bstrClassObj.m_str));

USES_CONVERSION;

CWnd* pWndMain = AfxGetMainWnd();
MessageBox( pWndMain ? pWndMain->m_hWnd : NULL, OLE2T(bstrClassObj), “Result parameters”, MB_OK);

pOutParam->Release();
}

if (NULL != pClassObj) pClassObj->Release();
if (NULL != pInParam) pInParam->Release();
if (NULL != pInClass) pInClass->Release();
if (NULL != pOutClass) pOutClass->Release();

return hres;
}


///////////////////////////////////////////////////////////////////////
//7) And finally the GetClassMethodsWMI returns through CStringArray
// argument the array of all class object methods.
///////////////////////////////////////////////////////////////////////

HRESULT GetClassMethodsWMI ( IN IWbemClassObject* piappObj,
OUT CStringArray& csarrMethods)
{

if (NULL == piappObj)
return E_INVALIDARG;

csarrMethods.RemoveAll();

USES_CONVERSION;

HRESULT hres;
hres = piappObj->BeginMethodEnumeration(0);

while(WBEM_S_NO_ERROR == hres)
{
CComBSTR bstrMethodName;
hres = piappObj->NextMethod(0, &bstrMethodName, NULL, NULL);

if (WBEM_S_NO_ERROR == hres)
csarrMethods.SetAtGrow(csarrMethods.GetSize(), OLE2T(bstrMethodName));
}

return piappObj->EndMethodEnumeration();
}

Thats all (meantime).

Good luck!!!

Downloads


Download demo project – 64.0 Kb


Download source – 4 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read