예제: 로컬 컴퓨터에서 WMI 데이터 가져오기

이 항목의 절차 및 코드 예제를 사용하여 COM 초기화를 수행하고, 로컬 컴퓨터에서 WMI에 연결하고, 반동기적으로 데이터를 검색한 후 정리하는 완전한 WMI 클라이언트 애플리케이션을 만들 수 있습니다. 이 예제에서는 로컬 컴퓨터의 운영 체제 이름을 가져와서 표시합니다. 원격 컴퓨터에서 데이터를 검색하려면 예: 원격 컴퓨터에서 WMI 데이터 가져오기를 참조하세요. 데이터를 비동기적으로 가져오는 방법은 예: 로컬 컴퓨터에서 비동기적으로 WMI 데이터 가져오기를 참조하세요.

다음 절차는 WMI 애플리케이션을 실행하는 데 사용됩니다. 1~5단계에서는 WMI를 설정하고 연결하며, 6~7단계에서는 데이터를 쿼리하고 수신합니다.

  1. CoInitializeEx를 호출하여 COM 매개 변수를 초기화합니다.

    자세한 내용은 WMI 응용 프로그램에 대한 COM 초기화를 참조하세요.

  2. CoInitializeSecurity를 호출하여 COM 프로세스 보안을 초기화합니다.

    자세한 내용은 C++를 사용하여 기본 프로세스 보안 수준 설정을 참조하세요.

  3. CoCreateInstance를 호출하여 WMI에 대한 초기 로케이터를 가져옵니다.

    자세한 내용은 WMI 네임스페이스에 대한 연결 만들기를 참조하세요.

  4. IWbemLocator::ConnectServer를 호출하여 로컬 컴퓨터에서 root\cimv2 네임스페이스의 IWbemServices에 대한 포인터를 가져옵니다. 원격 컴퓨터에 연결하려면 예: 원격 컴퓨터에서 WMI 데이터 가져오기를 참조하세요.

    자세한 내용은 WMI 네임스페이스에 대한 연결 만들기를 참조하세요.

  5. WMI 서비스가 CoSetProxyBlanket을 호출하여 클라이언트를 가장할 수 있도록 IWbemServices 프록시 보안을 설정합니다.

    자세한 내용은 WMI 연결에서 보안 수준 설정을 참조하세요.

  6. IWbemServices 포인터를 사용하여 WMI의 요청을 수행합니다. 이 예제에서는 IWbemServices::ExecQuery를 호출하여 운영 체제 이름에 대한 쿼리를 실행합니다.

    다음 WQL 쿼리는 메서드 인수 중 하나입니다.

    SELECT * FROM Win32_OperatingSystem

    이 쿼리의 결과는 IEnumWbemClassObject 포인터에 저장됩니다. 이를 통해 IEnumWbemClassObject 인터페이스를 사용하여 쿼리의 데이터 개체를 반동기적으로 검색할 수 있습니다. 자세한 내용은 WMI 열거를 참조하세요. 데이터를 비동기적으로 가져오는 방법은 예: 로컬 컴퓨터에서 비동기적으로 WMI 데이터 가져오기를 참조하세요.

    WMI에 대해 요청을 수행하는 방법에 대한 자세한 내용은 클래스 및 인스턴스 정보 조작, WMI 쿼리메서드 호출을 참조하세요.

  7. WQL 쿼리에서 데이터를 가져와서 표시합니다. IEnumWbemClassObject 포인터는 쿼리가 반환한 데이터 개체에 연결되어 있고, 데이터 개체는 IEnumWbemClassObject::Next 메서드를 사용하여 검색할 수 있습니다. 이 메서드는 데이터 개체를 메서드에 전달된 IWbemClassObject 포인터에 연결합니다. IWbemClassObject::Get 메서드를 사용하여 데이터 개체에서 원하는 정보를 가져옵니다.

    다음 코드 예제는 데이터 개체에서 운영 체제의 이름을 제공하는 이름 속성을 가져오는 데 사용됩니다.

    VARIANT vtProp;
    VariantInit(&vtProp);
    // Get the value of the Name property
    hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
    

    이름 속성의 값이 VARIANT 변수 vtProp에 저장되면 사용자에게 이름을 표시할 수 있습니다.

    자세한 내용은 WMI 열거를 참조하세요.

다음 코드 예제에서는 로컬 컴퓨터에서 WMI 데이터를 반동기적으로 검색합니다.

#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

#pragma comment(lib, "wbemuuid.lib")

int main(int argc, char **argv)
{
    HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x" 
            << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------

    hres =  CoInitializeSecurity(
        NULL, 
        -1,                          // COM authentication
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        NULL                         // Reserved
        );

                      
    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x" 
            << hex << hres << endl;
        CoUninitialize();
        return 1;                    // Program has failed.
    }
    
    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);
 
    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object."
            << " Err code = 0x"
            << hex << hres << endl;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

    // Step 4: -----------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;
 
    // Connect to the root\cimv2 namespace with
    // the current user and obtain pointer pSvc
    // to make IWbemServices calls.
    hres = pLoc->ConnectServer(
         _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
         NULL,                    // User name. NULL = current user
         NULL,                    // User password. NULL = current
         0,                       // Locale. NULL indicates current
         NULL,                    // Security flags.
         0,                       // Authority (for example, Kerberos)
         0,                       // Context object 
         &pSvc                    // pointer to IWbemServices proxy
         );
    
    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" 
             << hex << hres << endl;
        pLoc->Release();     
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


    // Step 5: --------------------------------------------------
    // Set security levels on the proxy -------------------------

    hres = CoSetProxyBlanket(
       pSvc,                        // Indicates the proxy to set
       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
       NULL,                        // Server principal name 
       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
       NULL,                        // client identity
       EOAC_NONE                    // proxy capabilities 
    );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----

    // For example, get the name of the operating system
    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"), 
        bstr_t("SELECT * FROM Win32_OperatingSystem"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
        NULL,
        &pEnumerator);
    
    if (FAILED(hres))
    {
        cout << "Query for operating system name failed."
            << " Error code = 0x" 
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------
 
    IWbemClassObject *pclsObj = NULL;
    ULONG uReturn = 0;
   
    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, 
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

        VariantInit(&vtProp);
        // Get the value of the Name property
        hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
        wcout << " OS Name : " << vtProp.bstrVal << endl;
        VariantClear(&vtProp);

        pclsObj->Release();
    }

    // Cleanup
    // ========
    
    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    CoUninitialize();

    return 0;   // Program successfully completed.
 
}