範例:從本機電腦取得 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. 設定 IWbemServices Proxy 安全性,讓 WMI 服務可以藉由呼叫 CoSetProxyBlanket來模擬用戶端。

    如需詳細資訊,請參閱 在 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 方法可從資料物件取得所需的資訊。

    下列程式碼範例用來從提供作業系統名稱的資料物件取得 Name 屬性。

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

    在 Name 屬性的值儲存在 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.
 
}