擷取 WMI 實例的一部分

部分實例擷取是在 WMI 只擷取實例屬性的子集時。 例如,WMI 只能擷取 NameKey 屬性。 部分實例擷取最常見的用法是在具有多個屬性的大型列舉上。

使用 PowerShell 擷取 WMI 實例的一部分

您可以使用 Get-WmiObject來擷取實例的個別屬性;屬性本身可以擷取並顯示數種方式。 如同擷取實例,PowerShell 預設會傳回指定類別的所有實例;如果您想要只擷取單一實例,則必須指定特定值。

下列程式碼範例會顯示 Win32_LogicalDisk 類別實例的磁片區序號。

(Get-WmiObject -class Win32_logicalDisk).DeviceID

#or

Get-WmiObject -class Win32_LogicalDisk | format-list DeviceID

#or

$myDisk = Get-WmiObject -class Win32_LogicalDisk
$myDisk.DeviceID

使用 C# (System.Management) 擷取 WMI 實例的一部分

您可以使用特定實例的詳細資料建立新的 ManagementObject ,以擷取實例的個別屬性。 然後,您可以使用 GetPropertyValue 方法隱含擷取實例的一或多個屬性。

注意

System.Management 是用來存取 WMI 的原始 .NET 命名空間;不過,此命名空間中的 API 通常較慢,而且不會相對於其較新式 的 Microsoft.Management.Infrastructure 對應專案進行調整。

下列程式碼範例會顯示 Win32_LogicalDisk 類別實例的磁片區序號。

using System.Management;
...
ManagementObject myDisk = new ManagementObject("Win32_LogicalDisk.DeviceID='C:'");
string myProperty = myDisk.GetPropertyValue("VolumeSerialNumber").ToString();
Console.WriteLine(myProperty);

使用 VBScript 擷取 WMI 實例的一部分

您可以使用 GetObject擷取實例的個別屬性。

下列程式碼範例會顯示 Win32_LogicalDisk 類別實例的磁片區序號。

MsgBox (GetObject("WinMgmts:Win32_LogicalDisk='C:'").VolumeSerialNumber)

使用 C++ 擷取 WMI 實例的一部分

下列程式是用來使用 C++ 要求部分實例擷取。

使用 C++ 要求部分實例擷取

  1. 使用CoCreateInstance的呼叫建立IWbemCoNtext物件。

    內容物件是 WMI 用來將詳細資訊傳遞至 WMI 提供者的物件。 在此情況下,您會使用 IWbemCoNtext 物件來指示提供者處理部分實例擷取。

  2. 新增__GET_EXTENSIONS、__GET_EXT_CLIENT_REQUEST,以及描述您想要擷取至 IWbemCoNtext 物件之屬性的任何其他具名值。

    下表列出擷取呼叫中使用的不同具名值。

    具名值 描述
    __GET_EXTENSIONS
    VT_BOOL 設定為 VARIANT_TRUE。 用來表示正在使用部分實例擷取作業。 這可讓您快速、單一檢查,而不需要列舉整個內容物件。 如果使用其他任何值,則必須使用這個值。
    __GET_EXT_PROPERTIES
    列出要擷取之屬性的字串SAFEARRAY。 無法與 __GET_EXT_KEYS_ONLY同時指定。
    星號 「*」 是__GET_EXT_PROPERTIES不正確屬性名稱。
    __GET_EXT_KEYS_ONLY
    VT_BOOL 設定為 VARIANT_TRUE。 表示只應該在傳回的 物件中提供索引鍵。 無法與 __GET_EXT_PROPERTIES同時指定。 相反地,優先于__GET_EXT_PROPERTIES。
    __GET_EXT_CLIENT_REQUEST
    VT_BOOL 設定為 VARIANT_TRUE。 表示呼叫端是將值寫入至內容物件,且未從另一個相依作業傳播的值。
  3. 透過pCtx參數將IWbemCoNtext內容物件傳遞至IWbemServices::GetObjectIWbemServices::GetObjectAsyncIWbemServices::CreateInstanceEnumIWbemServices::CreateInstanceEnumAsync的任何呼叫。

    傳遞 IWbemCoNtext 物件會指示提供者允許部分實例擷取。 在完整實例擷取中,您會將 pCtx 設定為 Null 值。 如果提供者不支援部分實例擷取,您會收到錯誤訊息。

如果提供者不符合部分實例作業,提供者會繼續執行,就像您未輸入內容物件一樣,否則會傳回 WBEM_E_UNSUPPORTED_PARAMETER

下列範例描述如何執行 Win32_LogicalDisk的完整實例擷取,然後執行 Win32_LogicalDisk.Caption 屬性的部分實例擷取。

#include <stdio.h>
#define _WIN32_DCOM
#include <wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
#include <iostream>
using namespace std;
#include <comdef.h>


void main(void)
{
    HRESULT hr;
    _bstr_t bstrNamespace;
    IWbemLocator *pWbemLocator = NULL;
    IWbemServices *pServices = NULL;
    IWbemClassObject *pDrive = NULL;
    

    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    hr = CoInitializeSecurity(NULL, -1, NULL, NULL,
                         RPC_C_AUTHN_LEVEL_CONNECT,
                         RPC_C_IMP_LEVEL_IMPERSONATE,
                         NULL, EOAC_NONE, 0);
 
    if (FAILED(hr))
    {
       CoUninitialize();
       cout << "Failed to initialize security. Error code = 0x" 
            << hex << hr << endl;
       return;
    }

    hr = CoCreateInstance(CLSID_WbemLocator, NULL, 
                          CLSCTX_INPROC_SERVER, IID_IWbemLocator, 
                          (void**) &pWbemLocator);
    if( FAILED(hr) ) 
    {
        CoUninitialize();
        printf("failed CoCreateInstance\n");
        return;
    }
    
    bstrNamespace = L"root\\cimv2";
    hr = pWbemLocator->ConnectServer(bstrNamespace, 
              NULL, NULL, NULL, 0, NULL, NULL, &pServices);
    if( FAILED(hr) ) 
    {
        pWbemLocator->Release();
        CoUninitialize();
        printf("failed ConnectServer\n");
        return;
    }
    pWbemLocator->Release();
    printf("Successfully connected to namespace.\n");

    
    BSTR bstrPath = 
         SysAllocString(L"Win32_LogicalDisk.DeviceID=\"C:\"");
   // *******************************************************//
   // Perform a full-instance retrieval. 
   // *******************************************************//
    hr = pServices->GetObject(bstrPath,
                              0,0, &pDrive, 0);
    if( FAILED(hr) )
    { 
        pServices->Release();
        CoUninitialize();
        printf("failed GetObject\n");
        return;
    }    
    // Display the object
    BSTR  bstrDriveObj;
    hr = pDrive->GetObjectText(0, &bstrDriveObj);
    printf("%S\n\n", bstrDriveObj);

    pDrive->Release();
    pDrive = NULL;

   // *****************************************************//
   // Perform a partial-instance retrieval. 
   // *****************************************************//
    
    IWbemContext  *pctxDrive; // Create context object
    hr = CoCreateInstance(CLSID_WbemContext, NULL, 
                          CLSCTX_INPROC_SERVER, IID_IWbemContext, 
                          (void**) &pctxDrive);
    if (FAILED(hr))
    {
        pServices->Release();
        pDrive->Release();    
        CoUninitialize();
        printf("create instance failed for context object.\n");
        return;
    }
    
    VARIANT  vExtensions;
    VARIANT  vClient;
    VARIANT  vPropertyList;
    VARIANT  vProperty;
    SAFEARRAY  *psaProperties;
    SAFEARRAYBOUND saBounds;
    LONG  lArrayIndex = 0;
    
    // Add named values to the context object. 
    VariantInit(&vExtensions);
    V_VT(&vExtensions) = VT_BOOL;
    V_BOOL(&vExtensions) = VARIANT_TRUE;
    hr = pctxDrive->SetValue(_bstr_t(L"__GET_EXTENSIONS"), 
        0, &vExtensions);
    VariantClear(&vExtensions);

    VariantInit(&vClient);
    V_VT(&vClient) = VT_BOOL;
    V_BOOL(&vClient) = VARIANT_TRUE;
    hr = pctxDrive->SetValue(_bstr_t(L"__GET_EXT_CLIENT_REQUEST"), 
       0, &vClient);
    VariantClear(&vClient);
    // Create an array of properties to return.
    saBounds.cElements = 1;
    saBounds.lLbound = 0;
    psaProperties = SafeArrayCreate(VT_BSTR, 1, &saBounds);

    // Add the Caption property to the array.
    VariantInit(&vProperty);
    V_VT(&vProperty) = VT_BSTR;
    V_BSTR(&vProperty) = _bstr_t(L"Caption");
    SafeArrayPutElement(psaProperties, &lArrayIndex, 
       V_BSTR(&vProperty));
    VariantClear(&vProperty);
    
    VariantInit(&vPropertyList);
    V_VT(&vPropertyList) = VT_ARRAY | VT_BSTR;
    V_ARRAY(&vPropertyList) = psaProperties;
    // Put the array in the named value __GET_EXT_PROPERTIES.
    hr = pctxDrive->SetValue(_bstr_t(L"__GET_EXT_PROPERTIES"), 
        0, &vPropertyList);
    VariantClear(&vPropertyList);
    SafeArrayDestroy(psaProperties);

    // Pass the context object as the pCtx parameter of GetObject.
    hr = pServices->GetObject(bstrPath, 0, pctxDrive, &pDrive, 0);
    if( FAILED(hr) )
    { 
        pServices->Release();
        CoUninitialize();
        printf("failed property GetObject\n");
        return;
    }    
    // Display the object
    hr = pDrive->GetObjectText(0, &bstrDriveObj);
    printf("%S\n\n", bstrDriveObj);

    SysFreeString(bstrPath);

    VARIANT vFileSystem;
    // Attempt to get a property that was not requested.
    // The following should return a NULL property if
    // the partial-instance retrieval succeeded.

    hr = pDrive->Get(_bstr_t(L"FileSystem"), 0,
                       &vFileSystem, NULL, NULL);

    if( FAILED(hr) )
    { 
        pServices->Release();
        pDrive->Release();    
        CoUninitialize();
        printf("failed get for file system\n");
        return;
    }    
 
    if (V_VT(&vFileSystem) == VT_NULL)
        printf("file system variable is null - expected\n");
    else
        printf("FileSystem = %S\n", V_BSTR(&vFileSystem));
    
    VariantClear(&vFileSystem);

    pDrive->Release();    
    pctxDrive->Release();
    pServices->Release();
    pServices = NULL;    // MUST be set to NULL
    CoUninitialize();
    return;  // -- program successfully completed
};

執行時,先前的程式碼範例會撰寫下列資訊。 第一個物件描述來自完整實例擷取。 第二個物件描述來自部分實例擷取。 最後一節顯示,如果您要求原始GetObject呼叫中未要求的屬性,就會收到Null值。

Successfully connected to namespace

instance of Win32_LogicalDisk
{
        Caption = "C:";
        Compressed = FALSE;
        CreationClassName = "Win32_LogicalDisk";
        Description = "Local Fixed Disk";
        DeviceID = "C:";
        DriveType = 3;
        FileSystem = "NTFS";
        FreeSpace = "3085668352";
        MaximumComponentLength = 255;
        MediaType = 12;
        Name = "C:";
        Size = "4581445632";
        SupportsFileBasedCompression = TRUE;
        SystemCreationClassName = "Win32_ComputerSystem";
        SystemName = "TITUS";
        VolumeName = "titus-c";
        VolumeSerialNumber = "7CB4B90E";
};

instance of Win32_LogicalDisk
{
        Caption = "C:";
        CreationClassName = "Win32_LogicalDisk";
        Description = "Local Fixed Disk";
        DeviceID = "C:";
        DriveType = 3;
        MediaType = 12;
        Name = "C:";
        SystemCreationClassName = "Win32_ComputerSystem";
        SystemName = "MySystem";
};

下列輸出是由上一個範例所產生。

file system variable is null - expected
Press any key to continue