Click here to Skip to main content
15,896,269 members
Articles / Programming Languages / C++

Making WMI Queries In C++

Rate me:
Please Sign up or sign in to vote.
4.92/5 (70 votes)
30 May 200527 min read 539K   10.9K   159  
An example-driven guide on how to write WMI consumers in C++.
#ifndef _WIN32_DCOM
#define _WIN32_DCOM
#endif

#include <windows.h>
#include <objbase.h>
#include <atlbase.h>
#include <iostream>
#include <wbemidl.h>
#include <comutil.h>


int main( int argc, char** argv )
{
	HRESULT hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
	if ( FAILED( hr ) )
	{
		std::cerr << "COM initialization failed" << std::endl;
		return -1;
	}

	// setup process-wide security context
	hr = CoInitializeSecurity( NULL, // we're not a server
							   -1, // we're not a server
							   NULL, // dito
							   NULL, // reserved
							   RPC_C_AUTHN_LEVEL_DEFAULT, // let DCOM decide
							   RPC_C_IMP_LEVEL_IMPERSONATE,
							   NULL,
							   EOAC_NONE,
							   NULL );
	if ( FAILED( hr ) )
	{
		std::cerr << "Security initialization failed" << std::endl;
		return -1;
	}

	int result = 0;
	// we're going to use CComPtr<>s, whose lifetime must end BEFORE CoUnitialize is called
	{
		// connect to WMI
		CComPtr< IWbemLocator > locator;
		hr = CoCreateInstance( CLSID_WbemAdministrativeLocator, NULL,
							CLSCTX_INPROC_SERVER,
							IID_IWbemLocator, reinterpret_cast< void** >( &locator ) );
		if ( FAILED( hr ) )
		{
			std::cerr << "Instantiation of IWbemLocator failed" << std::endl;
			return -1;
		}

		// connect to local service with current credentials
		CComPtr< IWbemServices > service;
		hr = locator->ConnectServer( L"root\\cimv2", NULL, NULL, NULL,
									 WBEM_FLAG_CONNECT_USE_MAX_WAIT,
									 NULL, NULL, &service );
		if ( SUCCEEDED( hr ) )
		{
			// execute a query
			CComPtr< IEnumWbemClassObject > enumerator;
			hr = service->ExecQuery( L"WQL", L"SELECT * FROM Win32_Processor",
								     WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator );
			if ( SUCCEEDED( hr ) )
			{
				// read the first instance from the enumeration (only one on single processor machines)
				CComPtr< IWbemClassObject > processor = NULL;
				ULONG retcnt;
				hr = enumerator->Next( WBEM_INFINITE, 1L, reinterpret_cast<IWbemClassObject**>( &processor ), &retcnt );
				if ( SUCCEEDED( hr ) )
				{
					if ( retcnt > 0 )
					{
						// we have a processor installed :)
						// now extract a property value
						_variant_t var_val;
						hr = processor->Get( L"Name", 0, &var_val, NULL, NULL );
						if ( SUCCEEDED( hr ) )
						{
							_bstr_t str = var_val;
							std::cout << "Processor name: " << str << std::endl;
						}
						else
						{
							std::cerr << "IWbemClassObject::Get failed" << std::endl;
							result = -1;
						}
					}
					else
					{
						std::cout << "Enumeration empty" << std::endl;
					}
				}
				else
				{
					std::cerr << "Error in iterating through enumeration" << std::cerr;
					result = -1;
				}
			}
			else
			{
				std::cerr << "Query failed" << std::endl;
				result = -1;
			}
		}
		else
		{
			std::cerr << "Couldn't connect to service" << std::endl;
			result = -1;
		}
	}
	CoUninitialize();

	return result;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Germany Germany

Still lacking an university degree in computer science, I have 20 years of experience in software development and implementation. Having expert knowledge in object-oriented programming languages like C++, Java and C# on Windows, LINUX and UNIX platforms, I participated in multiple research projects at the University of Oldenburg. During these assignments, I was trusted with implementation of a graphical editor for specification languages like CSP or Z and a prototypical tool for workflow data distribution and analysis. I gained experiences in a widespread spectrum of CS and software development topics, ranging from compiler construction across data base programming to MDA. My research interests include questions of graphical user interface design and component-based systems.


I consider myself an old-school CS geek. While I admit that simple tasks do not pose much of a problem and can be done in quick and efficient manner, it's the challenging ones that appeal to me. If you are looking for a skillful employee - be it on a permanent, contract or freelance basis - and if you can live with a lacking university degree, why not contacting me?


Comments and Discussions