CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> Windows Programming >> System >> Misc


Using WMI to Extract Management Information
Rating:

Rinat Sadikov (view profile)
May 21, 2001


(continued)



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

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
Bad CRC!!! - 61815sk (09/05/2006)
How fixed parameters String Array with ExecuteMethodWMI - azizaziz (03/07/2006)
ExecMethod - CObject (03/07/2005)
wbemidl.h - mythri_bl (09/22/2004)
Where is the auther ? - dharani (06/24/2004)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES