在C++中使用WMI类Msvm_SummaryInformation或Msvm_VirtualSystemManagementService查询虚拟机功能,可以通过以下步骤实现:
#include <iostream>
#include <comdef.h>
#include <Wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
using namespace std;
using namespace _com_util;
using namespace WbemServices;
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code: " << hex << hres << endl;
return 1;
}
hres = CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
NULL
);
if (FAILED(hres))
{
cout << "Failed to initialize security. Error code: " << hex << hres << endl;
CoUninitialize();
return 1;
}
IWbemLocator* pLoc = NULL;
hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
(LPVOID*)&pLoc
);
if (FAILED(hres))
{
cout << "Failed to create IWbemLocator object. Error code: " << hex << hres << endl;
CoUninitialize();
return 1;
}
IWbemServices* pSvc = NULL;
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\Virtualization\\V2"),
NULL,
NULL,
0,
NULL,
0,
0,
&pSvc
);
if (FAILED(hres))
{
cout << "Could not connect to WMI namespace. Error code: " << hex << hres << endl;
pLoc->Release();
CoUninitialize();
return 1;
}
hres = CoSetProxyBlanket(
pSvc,
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))
{
cout << "Failed to set proxy blanket. Error code: " << hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1;
}
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Msvm_SummaryInformation"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator
);
if (FAILED(hres))
{
cout << "Failed to execute query. Error code: " << hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1;
}
IWbemClassObject* pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
hres = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if (uReturn == 0)
{
break;
}
VARIANT vtProp;
hres = pclsObj->Get(L"ElementName", 0, &vtProp, 0, 0);
if (SUCCEEDED(hres))
{
wcout << "ElementName: " << vtProp.bstrVal << endl;
VariantClear(&vtProp);
}
pclsObj->Release();
}
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
CoUninitialize();
这样就可以在C++中使用WMI类Msvm_SummaryInformation或Msvm_VirtualSystemManagementService查询虚拟机功能了。请注意,以上代码仅为示例,实际应用中可能需要根据具体情况进行适当修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云