#include <iostream>
#include <comdef.h>
#include <Wbemidl.h>
#include <atlbase.h>
#include <atlstr.h>
# pragma comment(lib, "wbemuuid.lib")
创建普通console 项目,添加 ATL 支持
//
// 初始化 COM
//
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
return 1; // Program has failed.
}
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.
}
//
// CoCreateInstance 创建 Locator 实例 .
//
CComQIPtr< IWbemLocator> pLoc;
hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID *) &pLoc);
if (FAILED(hres))
{
CoUninitialize();
return 1; // Program has failed.
}
//
// 连接到 "root/cimv2" 命名空间,获得 IWbemServices 类型的指针
//
CComQIPtr< IWbemServices > pSvc;
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 (e.g. Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if (FAILED(hres))
{
CoUninitialize();
return 1; // Program has failed.
}
//
// 设置 IWbemServices 代理安全, 这样 WMI 服务相当于客户端使用
//
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))
{
CoUninitialize();
return 1;
}
//
// 使用 IWbemServices 指针请求 WMI, 得到有关操作系统的信息
//
CComQIPtr <IEnumWbemClassObject> pEnumerator ;
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))
{
CoUninitialize();
return 1; // Program has failed.
}
//
// 显示WQL查询数据
//
ULONG uReturn = 0;
while (pEnumerator)
{
CComQIPtr< IWbemClassObject > pclsObj ;
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if(0 == uReturn)
{
break;
}
_variant_t vtProp;
// 得到操作系统名字
hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0 );
// 得到系统启动分区
pclsObj->Get(L"BootDevice", 0, &vtProp, 0, 0 ) ;
// 得到当前运行的进程数
pclsObj->Get(L"NumberOfProcesses", 0, &vtProp, 0, 0 );
// 得到操作系统序列号
pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0 );
// 得到操作系统的语言
pclsObj->Get(L"OSLanguage", 0, &vtProp, 0, 0 );
//
// 由于这个属性是 read-only, 所以不能设置
// vtProp.lVal = 0x0809;
// pclsObj->Put( L"OSLanguage", 0/*reserved*/, &vtProp, VT_I4 );
//
// 得到制造商名称
//
pclsObj->Get(L"Manufacturer", 0, &vtProp, 0, 0 );
}
CoUninitialize();