how to read the contents of a log file that is retrieved using WQL using c++ - wmi

I am new to WMI.I tried to implement a java application that get the WQL query from the user and executes the query using a c++ native program which i call from the java application using JNI.I managed to make the WMI calls and retrieve the data.
My problem is that i am not able to read all the contents for the retrieved object.I read a log file whose header along with a single entry is a follows.
Header:
"Message","Id","Version","Qualifiers","Level","Task","Opcode","Keywords","RecordId","ProviderName","ProviderId","LogName","ProcessId","ThreadId","MachineName","UserId","TimeCreated","ActivityId","RelatedActivityId","ContainerLog","MatchedQueryIds","Bookmark","LevelDisplayName","OpcodeDisplayName","TaskDisplayName","KeywordsDisplayNames","Properties"
Single Entry :(I converted the log file to csv file just to view the contents)
"Windows service started.","2",,"4","5","0",,"36028357018723968","98","DigitalDelivery",,"Dell",,,"vignesh",,"14-01-2018 11:06:35",,,"c:\windows.old\windows\system32\winevt\logs\dell.evtx","System.UInt32[]","System.Diagnostics.Eventing.Reader.EventBookmark","Information","Info",,"System.Collection.ObjectModel.ReadOnlyCollection`1[System.String]","SystemCollections.Generic.List`[System.Diagnostics.EventingReader.EventProperty]"
c++ prgram to connect to WMI
#define _WIN32_DCOM
#include <iostream>
using namespace std ;
#include <wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
#include <windows.h>
#include <jni.h>
#include "WmiClientClassTwo.h"
#include <comdef.h>
JNIEXPORT void JNICALL Java_WmiClientClassTwo_createConnection(JNIEnv *env, jobject obj,jstring jquery)
{
const char *Cquery = env->GetStringUTFChars(jquery,NULL);
cout << "query string is :::" << Cquery << endl ;
// Initializing the COM
HRESULT hr ;
hr = CoInitializeEx( 0 , COINIT_MULTITHREADED );
if(FAILED(hr))
{
cout << "failed to initialize COM Library " << hex << hr << endl ;
return;
}
//Initialize COM security
hr = CoInitializeSecurity (
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
NULL
);
if(FAILED(hr))
{
cout << "failed to initilize security."<< hex << hr << endl ;
CoUninitialize();
return ;
}
cout << "Initilized the COM"<< endl ;
//Initializing the IWbemLocator throught a call to CoCreateInstance.
IWbemLocator *pLoc = 0 ;
hr = CoCreateInstance(CLSID_WbemLocator,0,CLSCTX_INPROC_SERVER,IID_IWbemLocator,(LPVOID*) & pLoc);
if(FAILED(hr))
{
cout << "failed to create IWbemLocator object"<< hex << hr << endl ;
CoUninitialize();
return ;
}
//Connect to WMI through a call to ConnectServer method of IWbemLocator
IWbemServices *pSvc = 0 ;
hr = pLoc->ConnectServer(
_bstr_t(L"ROOT\\CIMV2"),
NULL,
NULL,
0,
NULL,
0,
0,
&pSvc);
if(FAILED(hr))
{
cout << "could not connect to WMI from ConnectServer method"<<hex<<hr<<endl;
pLoc->Release();
CoUninitialize();
return ;
}
cout << "Connected to WMI" << endl ;
//Setting security level on a Wmi connection
hr = 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(hr))
{
cout << "could not set security level on wmi connection" << hex << hr << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return ;
}
cout << "Security level set on wmi connection" << endl;
// Querying for data using executeQuery Method of IWbemServies pointer
IEnumWbemClassObject* pEnumerator = NULL ;
hr = pSvc->ExecQuery (
bstr_t("WQL"),
// bstr_t("SELECT * FROM Win32_NTLogEvent Where (Logfile = 'Dell')"),
bstr_t(Cquery),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if(FAILED(hr))
{
cout << "Query for operating system failed" << hex << endl ;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return ;
}
cout << "data is obtained from the operating system" << endl ;
//Getting the data from the query
IWbemClassObject *pclsobj = NULL ;
ULONG uReturn = 0 ;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE,1,&pclsobj,&uReturn);
if( 0 == uReturn )
{
cout << "loop broke" << endl ;
break;
}
VARIANT vtProp;
hr = pclsobj->Get(L"Message",0,&vtProp,0,0);
wcout << "Message : " << vtProp.bstrVal << endl ;
VariantClear(&vtProp);
hr = pclsobj->Get(L"ComputerName",0,&vtProp,0,0);
wcout << "ComputerName : " << vtProp.bstrVal << endl;
VariantClear(&vtProp);
hr = pclsobj->Get(L"Id",0,&vtProp,0,0);
wcout << "Id : " << vtProp.plVal << endl ;
VariantClear(&vtProp);
hr = pclsobj->Get(L"ProviderName",0,&vtProp,0,0);
wcout << "ProviderName : " << vtProp.bstrVal << endl ;
VariantClear(&vtProp);
hr = pclsobj->Get(L"Level",0,&vtProp,0,0);
wcout << "Level : " << vtProp.plVal << endl ;
VariantClear(&vtProp);
pclsobj->Release();
}
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
CoUninitialize();
return ;
}
when i execute the program only the Message and Computername properties are returning the correct value and all other fields are returning wrong values.
Can any one tell me how can i read all the fields in the retrieved log file.
the sample output of a single entry that i obtained is
Output:
SELECT * FROM Win32_NTLogEvent Where (Logfile = 'Dell')
query string is :::SELECT * FROM Win32_NTLogEvent Where (Logfile = 'Dell')
Initilized the COM
Connected to WMI
Security level set on wmi connection
data is obtained from the operating system
Message : Windows service started.
ComputerName : vignesh
Id : 0000000000E93A88
ProviderName : vignesh
0
Level : 0000000000000000
TimeCreated : 0000000000EA1798

This is because the query doesn't have the properties your asking for. If you run GetNames method and print the property names, you'll get a similar result to this one,
Category
CategoryString
ComputerName
Data
EventCode
EventIdentifier
EventType
InsertionStrings
Logfile
Message
RecordNumber
SourceName
TimeGenerated
TimeWritten
Type
User
You can only access these properties.As you can see, there is no property named ID, hence you're getting garbage values. Hope this helps!

Related

How can I find out the command line arguments of a running application? [duplicate]

How do I get the command line arguments of all running processes in Windows using WMI in the C language?
You must use the Win32_Process WMI class and check the value of the CommandLine property, also take a look to this article How do I get the command line of another process which explains that string is ...just "preinitialized variable", a process could in principle (and many do in practice, although usually inadvertently) write to the memory that holds the command line
Update
C Sample
#define _WIN32_WINNT 0x0400
#define _WIN32_DCOM
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <wbemidl.h>
void _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = 0;
IWbemLocator *WbemLocator = NULL;
IWbemServices *WbemServices = NULL;
IEnumWbemClassObject *EnumWbem = NULL;
//initializate the Windows security
hr = CoInitializeEx(0, COINIT_MULTITHREADED);
hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
hr = CoCreateInstance(&CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, &IID_IWbemLocator, (LPVOID *) &WbemLocator);
//connect to the WMI
hr = WbemLocator->lpVtbl->ConnectServer(WbemLocator, L"ROOT\\CIMV2", NULL, NULL, NULL, 0, NULL, NULL, &WbemServices);
//Run the WQL Query
hr = WbemServices->lpVtbl->ExecQuery(WbemServices, L"WQL", L"SELECT ProcessId,CommandLine FROM Win32_Process", WBEM_FLAG_FORWARD_ONLY, NULL, &EnumWbem);
// Iterate over the enumerator
if (EnumWbem != NULL) {
IWbemClassObject *result = NULL;
ULONG returnedCount = 0;
while((hr = EnumWbem->lpVtbl->Next(EnumWbem, WBEM_INFINITE, 1, &result, &returnedCount)) == S_OK) {
VARIANT ProcessId;
VARIANT CommandLine;
// access the properties
hr = result->lpVtbl->Get(result, L"ProcessId", 0, &ProcessId, 0, 0);
hr = result->lpVtbl->Get(result, L"CommandLine", 0, &CommandLine, 0, 0);
if (!(CommandLine.vt==VT_NULL))
wprintf(L"%u %s \r\n", ProcessId.uintVal, CommandLine.bstrVal);
result->lpVtbl->Release(result);
}
}
// Release the resources
EnumWbem->lpVtbl->Release(EnumWbem);
WbemServices->lpVtbl->Release(WbemServices);
WbemLocator->lpVtbl->Release(WbemLocator);
CoUninitialize();
getchar();
}
Borland C++ Sample
#pragma hdrstop
#include <iostream>
using namespace std;
#include <wbemcli.h>
#include <comdef.h>
//CREDENTIAL structure
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v=vs.85%29.aspx
#define CRED_MAX_USERNAME_LENGTH 513
#define CRED_MAX_CREDENTIAL_BLOB_SIZE 512
#define CREDUI_MAX_USERNAME_LENGTH CRED_MAX_USERNAME_LENGTH
#define CREDUI_MAX_PASSWORD_LENGTH (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2)
// The Win32_Process class represents a sequence of events on a Win32 system. Any sequence consisting of the interaction of one or more processors or interpreters, some executable code, and a set of inputs, is a descendent (or member) of this class.
// Example: A client application running on a Win32 system.
#pragma argsused
int main(int argc, char* argv[])
{
wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH+1] = L"user";
wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1] = L"password";
BSTR strNetworkResource;
//To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource
bool localconn = true;
strNetworkResource = localconn ? L"\\\\.\\root\\CIMV2" : L"\\\\remote--machine\\root\\CIMV2";
COAUTHIDENTITY *userAcct = NULL ;
COAUTHIDENTITY authIdent;
// Initialize COM. ------------------------------------------
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Set general COM security levels --------------------------
if (localconn)
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
);
else
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IDENTIFY, // 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
if (localconn)
hres = pLoc->ConnectServer(
strNetworkResource, // 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
);
else
hres = pLoc->ConnectServer(
strNetworkResource, // Object path of WMI namespace
pszName, // User name
pszPwd, // User password
NULL, // Locale
NULL, // Security flags
NULL, // Authority
NULL, // Context object
&pSvc // IWbemServices proxy
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
cout << "Connected to root\\CIMV2 WMI namespace" << endl;
// Set security levels on the proxy -------------------------
if (localconn)
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
);
else
{
// Create COAUTHIDENTITY that can be used for setting security on proxy
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = wcslen (pszPwd);
authIdent.Password = (USHORT*)pszPwd;
authIdent.User = (USHORT*)pszName;
authIdent.UserLength = wcslen(pszName);
authIdent.Domain = 0;
authIdent.DomainLength = 0;
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
}
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Use the IWbemServices pointer to make requests of WMI ----
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery( L"WQL", L"SELECT CommandLine,ProcessId FROM Win32_Process",
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hres))
{
cout << "ExecQuery failed" << " Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Secure the enumerator proxy
if (!localconn)
{
hres = CoSetProxyBlanket(
pEnumerator, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
cout << "Could not set proxy blanket on enumerator. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
}
// Get the data from the WQL sentence
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if(0 == uReturn || FAILED(hr))
break;
VARIANT vtProp;
hr = pclsObj->Get(L"CommandLine", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "CommandLine : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
if ((vtProp.vt & VT_ARRAY))
wcout << "CommandLine : " << "Array types not supported (yet)" << endl;
else
wcout << "CommandLine : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"ProcessId", 0, &vtProp, 0, 0);// Uint32
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "ProcessId : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
if ((vtProp.vt & VT_ARRAY))
wcout << "ProcessId : " << "Array types not supported (yet)" << endl;
else
wcout << "ProcessId : " << vtProp.uintVal << endl;
}
VariantClear(&vtProp);
pclsObj->Release();
pclsObj=NULL;
}
// Cleanup
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
if (pclsObj!=NULL)
pclsObj->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0; // Program successfully completed.
}

How to retrieve values from WIN32_NetworkAdapter using WMI in C++? I am unable to understand the VARIANT used to access the values after the query

Win_32 NetworkAdapter, Win32_SignedDriver,
How to retrieve values from WIN32_NetworkAdapter using WMI in C++? I am unable to understand the VARIANT used to access the values after the query.
The MSDN has a lot of resources about the WMI and C++, Also if you are new to use the WMI from C++, you can use the WMI Delphi Code Creator which allows you to generate C++ Code to access the WMI classes, events and methods.
Try this sample code generated by the application
#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
//CREDENTIAL structure
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v=vs.85%29.aspx
#define CRED_MAX_USERNAME_LENGTH 513
#define CRED_MAX_CREDENTIAL_BLOB_SIZE 512
#define CREDUI_MAX_USERNAME_LENGTH CRED_MAX_USERNAME_LENGTH
#define CREDUI_MAX_PASSWORD_LENGTH (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2)
#pragma argsused
int main(int argc, char* argv[])
{
wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH+1] = L"user";
wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1] = L"password";
BSTR strNetworkResource;
//To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource
bool localconn = true;
strNetworkResource = localconn ? L"\\\\.\\root\\CIMV2" : L"\\\\remote--machine\\root\\CIMV2";
COAUTHIDENTITY *userAcct = NULL ;
COAUTHIDENTITY authIdent;
// Initialize COM. ------------------------------------------
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Set general COM security levels --------------------------
if (localconn)
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
);
else
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IDENTIFY, // 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
if (localconn)
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // 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
);
else
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // Object path of WMI namespace
_bstr_t(pszName), // User name
_bstr_t(pszPwd), // User password
NULL, // Locale
NULL, // Security flags
NULL, // Authority
NULL, // Context object
&pSvc // IWbemServices proxy
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
cout << "Connected to root\\CIMV2 WMI namespace" << endl;
// Set security levels on the proxy -------------------------
if (localconn)
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
);
else
{
// Create COAUTHIDENTITY that can be used for setting security on proxy
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = wcslen (pszPwd);
authIdent.Password = (USHORT*)pszPwd;
authIdent.User = (USHORT*)pszName;
authIdent.UserLength = wcslen(pszName);
authIdent.Domain = 0;
authIdent.DomainLength = 0;
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
}
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Use the IWbemServices pointer to make requests of WMI ----
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery( L"WQL", L"SELECT * FROM Win32_NetworkAdapter",
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hres))
{
cout << "ExecQuery failed" << " Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Secure the enumerator proxy
if (!localconn)
{
hres = CoSetProxyBlanket(
pEnumerator, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
cout << "Could not set proxy blanket on enumerator. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
}
// Get the data from the WQL sentence
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if(0 == uReturn || FAILED(hr))
break;
VARIANT vtProp;
hr = pclsObj->Get(L"AdapterType", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "AdapterType : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "AdapterType : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"AdapterTypeId", 0, &vtProp, 0, 0);// Uint16
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "AdapterTypeId : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "AdapterTypeId : " << vtProp.uiVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "Caption : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "Caption : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"Description", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "Description : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "Description : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"MACAddress", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "MACAddress : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "MACAddress : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
pclsObj->Release();
pclsObj=NULL;
}
// Cleanup
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
if (pclsObj!=NULL)
pclsObj->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0; // Program successfully completed.
}
A query returns an instance of IEnumWbemClassObject interface. You can use it to enumerate objects. Objects are returned as IWbemClassObject instances. Then, you can use IWbemClassObject::Get method to get the properties.
See this MSDN sample; however, I normally use CComPtr<> ATL class instead of raw interface pointers, same with CComVariant versus raw VARIANT.

C++ Builder WMI : Invalid Query

Using C++ Builder XE4, I am trying to read Win32_DiskDrive Information, but I am not successful.
UnicodeString s;
Variant vX, vY, vZ, vi;
vX = Variant::CreateObject(L"WbemScripting.SWbemLocator");
vY = vX.OleFunction(L"ConnectServer");
vZ = vY.OleFunction(L"ExecQuery", L"SELECT * FROM Win32_DiskDrive");
int n = vZ.OlePropertyGet(L"Count"); // Error
s.SetLength(0);
for (int i = 0; i < n; i++) {
vi = vZ.OleFunction<int>(L"ItemIndex", i);
s = vi.OlePropertyGet(L"Caption");
RichEdit1->Lines->Add(s);
}
I received Error Message "Invalid Query" at
int n = vZ.OlePropertyGet(L"Count"); // Error
When I check the vZ, the IDE shows "{ { } }". Does this mean that I made mistake at getting vZ or somewhere before?
My environment is Windows7 Professional.
Any correction on the above code will be helpful.
The most common way to access the WMI from C++ is using WMI COM client (wbemcli.h) directly.
Try this sample.
#pragma hdrstop
#include <iostream>
using namespace std;
#include <wbemcli.h>
#include <comdef.h>
#pragma argsused
int main(int argc, char* argv[])
{
BSTR strNetworkResource;
strNetworkResource = L"\\\\.\\root\\CIMV2";
// Initialize COM. ------------------------------------------
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
hres = pLoc->ConnectServer(
strNetworkResource, // 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))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
cout << "Connected to root\\CIMV2 WMI namespace" << endl;
// 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;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Use the IWbemServices pointer to make requests of WMI ----
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery( L"WQL", L"SELECT * FROM Win32_DiskDrive",
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hres))
{
cout << "ExecQuery failed" << " Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Get the data from the WQL sentence
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if(0 == uReturn || FAILED(hr))
break;
VARIANT vtProp;
hr = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "Caption : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
if ((vtProp.vt & VT_ARRAY))
wcout << "Caption : " << "Array types not supported (yet)" << endl;
else
wcout << "Caption : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"DeviceID", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "DeviceID : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
if ((vtProp.vt & VT_ARRAY))
wcout << "DeviceID : " << "Array types not supported (yet)" << endl;
else
wcout << "DeviceID : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
pclsObj->Release();
pclsObj=NULL;
}
// Cleanup
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
if (pclsObj!=NULL)
pclsObj->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0; // Program successfully completed.
}
Note: If you are new to interact with the WMI from C++ you can use the WMI Delphi Code Creator which can help you explore the WMI properties and create C++ code to access the WMI.
I would suppose that if you made the code to look a bit more user friendly that would help:
UnicodeString s;
Variant vX, vY, vZ, vi;
vX = Variant::CreateObject(L"WbemScripting.SWbemLocator");
vY = vX.OleFunction(L"ConnectServer");
vZ = vY.OleFunction(L"ExecQuery", L"SELECT * FROM Win32_DiskDrive");
int n = vZ.OlePropertyGet(L"Count"); // Error
s.SetLength(0);
for (int i = 0; i < n; i++) {
vi = vZ.OleFunction<int>(L"ItemIndex", i);
s = vi.OlePropertyGet(L"Caption");
RichEdit1->Lines->Add(s);
}
try this:
RichEdit1->Lines->Clear();
Variant l = Variant::CreateObject("WbemScripting.SWbemLocator");
Variant svc = l.OleFunction("ConnectServer");
Variant objs = svc.OleFunction("ExecQuery", OleVariant("SELECT * FROM Win32_DiskDrive"));
Variant n = objs.OlePropertyGet("Count"); // Error
for (int i = 0; i < n; i++)
{
Variant obj = objs.OleFunction<int>("ItemIndex", OleVariant(i));
Variant props = obj.OlePropertyGet("Properties_");
Variant prop = props.OleFunction("Item", OleVariant("Caption"));
String Value = prop.OlePropertyGet("Value");
RichEdit1->Lines->Add(Value);
}

Call WMIC commands in c++ code

I am trying to re-write a logic that i had written in batch script into a c++ code and a DLL consequently.
In my batch script i was checking for command line arguments of all java processes using WMIC. Here is the script -
FOR /F "tokens=*" %%A IN ('2^>nul wmic process where^(name^="java.exe"^) get commandline ^| Findstr "XYZ"') DO SET Var=%%A
IF DEFINED Var (
cscript MessageBox.vbs "Message IN POP-UP."
GOTO :EOF
)
FOR /F "tokens=*" %%A IN ('2^>nul wmic process where^(name^="javaw.exe"^) get commandline ^| Findstr "XYZ"') DO SET Var=%%A
IF DEFINED Var (
cscript MessageBox.vbs "Message IN POP-UP."
GOTO :EOF
)
I want to re-use the same WMIC logic but now in a c++ code. Basically i want to avoid using vb scipt for the pop-up and i will call the "Message IN POP-UP" using some c++ commands.
Any starting points?? I could use system() call but then how would i do the checks like the one's i have written in the IF condition inside the batch script.
Instead of execute the WMIC application from C++, you can access to the WMI directly using COM. Try this sample app.
#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
# pragma comment(lib, "wbemuuid.lib")
//CREDENTIAL structure
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v=vs.85%29.aspx
#define CRED_MAX_USERNAME_LENGTH 513
#define CRED_MAX_CREDENTIAL_BLOB_SIZE 512
#define CREDUI_MAX_USERNAME_LENGTH CRED_MAX_USERNAME_LENGTH
#define CREDUI_MAX_PASSWORD_LENGTH (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2)
// The Win32_Process class represents a sequence of events on a Win32 system. Any sequence consisting of the interaction of one or more processors or interpreters, some executable code, and a set of inputs, is a descendent (or member) of this class.
// Example: A client application running on a Win32 system.
#pragma argsused
int main(int argc, char* argv[])
{
wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH+1] = L"user";
wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1] = L"password";
BSTR strNetworkResource;
//To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource
bool localconn = true;
strNetworkResource = localconn ? L"\\\\.\\root\\CIMV2" : L"\\\\remote--machine\\root\\CIMV2";
COAUTHIDENTITY *userAcct = NULL ;
COAUTHIDENTITY authIdent;
// Initialize COM. ------------------------------------------
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Set general COM security levels --------------------------
if (localconn)
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
);
else
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IDENTIFY, // 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
if (localconn)
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // 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
);
else
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // Object path of WMI namespace
_bstr_t(pszName), // User name
_bstr_t(pszPwd), // User password
NULL, // Locale
NULL, // Security flags
NULL, // Authority
NULL, // Context object
&pSvc // IWbemServices proxy
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
cout << "Connected to root\\CIMV2 WMI namespace" << endl;
// Set security levels on the proxy -------------------------
if (localconn)
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
);
else
{
// Create COAUTHIDENTITY that can be used for setting security on proxy
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = wcslen (pszPwd);
authIdent.Password = (USHORT*)pszPwd;
authIdent.User = (USHORT*)pszName;
authIdent.UserLength = wcslen(pszName);
authIdent.Domain = 0;
authIdent.DomainLength = 0;
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
}
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Use the IWbemServices pointer to make requests of WMI ----
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery( L"WQL", L"SELECT * FROM Win32_Process Where Name='java.exe'",
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hres))
{
cout << "ExecQuery failed" << " Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Secure the enumerator proxy
if (!localconn)
{
hres = CoSetProxyBlanket(
pEnumerator, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
cout << "Could not set proxy blanket on enumerator. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
}
// Get the data from the WQL sentence
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if(0 == uReturn || FAILED(hr))
break;
VARIANT vtProp;
hr = pclsObj->Get(L"CommandLine", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "CommandLine : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "CommandLine : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
pclsObj->Release();
pclsObj=NULL;
}
// Cleanup
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
if (pclsObj!=NULL)
pclsObj->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0; // Program successfully completed.
}
For an easy but ugly workaround, you could try to pass your query "by file"
use wmic, that works with the console.
Note that it will show a console every time you execute new system() command
So you use system("your query in wmic > youroutputfile.format") and retrieve through your c++
you could also execute a batch file if your query is a little more complicated
an example here:
system("wmic csproduct get name, identifyingnumber, uuid > c:\Temp\test.test");
wstring Return = MyReadingClass(L"c:\\Temp\\test.test").Read();
wmic offers you simplicity, which is what you should seek first.
This method is very easy and clear, but is very slow for real time processes due to HDD limitations + writing/reading operations + system security operations.

what's the C++ code of operating HNet_ConnectionProperties

Through VBScript here we can enumerate all network connections ( visible or not visible ). But I cannot find any C++ or COM codes to do this.
strServer = "."
Set objWMI = GetObject("winmgmts://" & strServer & "/root\Microsoft\HomeNet")
Set objInstances = objWMI.InstancesOf("HNet_ConnectionProperties",48)
On Error Resume Next
For Each objInstance in objInstances
With objInstance
WScript.Echo .Connection
WScript.Echo .IsIcsPrivate
WScript.Echo .IsIcsPublic
End With
On Error Goto 0
Next
This is the Equivalent C++ Code to access the HNet_ConnectionProperties WMI Class
#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
# pragma comment(lib, "wbemuuid.lib")
//CREDENTIAL structure
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v=vs.85%29.aspx
#define CRED_MAX_USERNAME_LENGTH 513
#define CRED_MAX_CREDENTIAL_BLOB_SIZE 512
#define CREDUI_MAX_USERNAME_LENGTH CRED_MAX_USERNAME_LENGTH
#define CREDUI_MAX_PASSWORD_LENGTH (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2)
#pragma argsused
int main(int argc, char* argv[])
{
wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH+1] = L"user";
wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1] = L"password";
BSTR strNetworkResource;
//To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource
bool localconn = true;
strNetworkResource = localconn ? L"\\\\.\\root\\Microsoft\\HomeNet" : L"\\\\remote--machine\\root\\Microsoft\\HomeNet";
COAUTHIDENTITY *userAcct = NULL ;
COAUTHIDENTITY authIdent;
// Initialize COM. ------------------------------------------
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Set general COM security levels --------------------------
if (localconn)
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
);
else
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IDENTIFY, // 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// 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;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
if (localconn)
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // 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
);
else
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // Object path of WMI namespace
_bstr_t(pszName), // User name
_bstr_t(pszPwd), // User password
NULL, // Locale
NULL, // Security flags
NULL, // Authority
NULL, // Context object
&pSvc // IWbemServices proxy
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
cout << "Connected to root\\Microsoft\\HomeNet WMI namespace" << endl;
// Set security levels on the proxy -------------------------
if (localconn)
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
);
else
{
// Create COAUTHIDENTITY that can be used for setting security on proxy
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = wcslen (pszPwd);
authIdent.Password = (USHORT*)pszPwd;
authIdent.User = (USHORT*)pszName;
authIdent.UserLength = wcslen(pszName);
authIdent.Domain = 0;
authIdent.DomainLength = 0;
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
}
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Use the IWbemServices pointer to make requests of WMI ----
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery( L"WQL", L"SELECT * FROM HNet_ConnectionProperties",
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hres))
{
cout << "ExecQuery failed" << " Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Secure the enumerator proxy
if (!localconn)
{
hres = CoSetProxyBlanket(
pEnumerator, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
cout << "Could not set proxy blanket on enumerator. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
}
// Get the data from the WQL sentence
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if(0 == uReturn || FAILED(hr))
break;
VARIANT vtProp;
hr = pclsObj->Get(L"Connection", 0, &vtProp, 0, 0);// Reference
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "Connection : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "Connection : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"IsBridge", 0, &vtProp, 0, 0);// Boolean
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "IsBridge : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "IsBridge : " << (vtProp.boolVal ? "True" : "False") << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"IsBridgeMember", 0, &vtProp, 0, 0);// Boolean
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "IsBridgeMember : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "IsBridgeMember : " << (vtProp.boolVal ? "True" : "False") << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"IsFirewalled", 0, &vtProp, 0, 0);// Boolean
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "IsFirewalled : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "IsFirewalled : " << (vtProp.boolVal ? "True" : "False") << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"IsIcsPrivate", 0, &vtProp, 0, 0);// Boolean
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "IsIcsPrivate : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "IsIcsPrivate : " << (vtProp.boolVal ? "True" : "False") << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"IsIcsPublic", 0, &vtProp, 0, 0);// Boolean
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "IsIcsPublic : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
wcout << "IsIcsPublic : " << (vtProp.boolVal ? "True" : "False") << endl;
}
VariantClear(&vtProp);
pclsObj->Release();
pclsObj=NULL;
}
// Cleanup
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
if (pclsObj!=NULL)
pclsObj->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0; // Program successfully completed.
}
Also consider use a tool like the Delphi WMI Code Creator, which can help you to generate c++ code to access the WMI.