Just another tech site

C# WMI and Management


Introduction:

WMI is an object-oriented repository that provides data about managed hardware and software. Central to WMI is the Common Information Model Object Manager (CIMOM) and a storage area called the CIM repository.

Reference:  http://msdn.microsoft.com/msdnmag/issues/05/09/WMI/default.aspx

ManagementObjectSearcher

the class that allows the retrieval of information.

SelectQuery q = new SelectQuery("Win32_Service", "State='Running'");
ManagementObjectSearcher s = new ManagementObjectSearcher(q);

foreach (ManagementObject service in s.Get())
{
    // show the instance
    Console.WriteLine(service.ToString());
}

Conect to remote machine : ManagementScope

the class that allows the retrieval of information.

// initialization des option de conection, securite etc...
ConnectionOptions oConn = new ConnectionOptions();
oConn.Authentication = AuthenticationLevel.Default;
oConn.Impersonation = ImpersonationLevel.Impersonate;
oConn.EnablePrivileges = true;
oConn.Username = "administrator";
oConn.Password = "password";

<span style="color:#339966;">// CONECTION</span>
oMs = newSystem.Management.<strong><span style="color:#ff0000;">ManagementScope</span></strong>(@"\\10.0.0.10\root\cimv2", oConn);</pre>
<h2>C# Code sample:</h2>
Reading the content of the EventLog
<pre style="border:solid 1px;background-color:#eeeeee;white-space:pre-wrap;margin:1px;padding:5px;"><span style="color:#339966;">// initialization</span>
ConnectionOptions oConn = null;
System.Management.ManagementScope oMs = null;
System.Management.ObjectQuery oQuery = null;
ManagementObjectSearcher oSearcher = null;
ManagementObjectCollection oReturnCollection = null;

<span style="color:#339966;">// initialization des option de conection, securite etc...</span>
oConn = new ConnectionOptions();
oConn.Authentication = AuthenticationLevel.Default;
oConn.Impersonation = ImpersonationLevel.Impersonate;
oConn.EnablePrivileges = true;
oConn.Username = "administrator";
oConn.Password = "password";

<span style="color:#339966;">// CONECTION</span>
oMs = newSystem.Management.ManagementScope(@"\\"+ULTAddress+"\root\cimv2", oConn);

<span style="color:#339966;">// REALIZING THE QUERY</span>
oQuery = new System.Management.ObjectQuery("<span style="color:#ff0000;">Select * from <strong>Win32_NTLogEvent</strong> </span>" );
//oQuery = new System.Management.ObjectQuery("<span style="color:#ff0000;">Select * from Win32_NTLogEvent Where TimeWritten &gt; '</span>"+from+"<span style="color:#ff0000;">' AND EventCode=6005</span> " );
//oQuery = new System.Management.ObjectQuery("<span style="color:#ff0000;">Select * from Win32_NTLogEvent Where Type = 'error'</span>");
//oQuery = new System.Management.ObjectQuery("<span style="color:#ff0000;">Select * from Win32_NTLogEvent Where LogFile='Application'</span>");

oSearcher = new ManagementObjectSearcher(oMs,oQuery) ;
oReturnCollection = oSearcher.Get();
foreach( ManagementObject mo in oReturnCollection )
{
    Console.WriteLine("EventCode ["+mo["EventCode"].ToString()+ "]");
    Console.WriteLine("\tSourceName :[ "+mo["SourceName"].ToString()+ " ]");
    Console.WriteLine("\tLogfile :[ "+mo["Logfile"].ToString()+ " ]");
    Console.WriteLine("\tTimeWritten:[ "+mo["TimeWritten"]+ " ]");
    Console.WriteLine("\tType :[ "+mo["Type"].ToString()+ " ]");
    Console.WriteLine("\tCategory :[ "+mo["Category"].ToString()+ " ]");
    Console.WriteLine("\tMessage :[ "+mo["Message"].ToString()+ " ]");
    Console.WriteLine("");
}

Pour information, la structure de la classe Win32_NTLogEvent est la suivante.

class <strong><span style="color:#ff0000;">Win32_NTLogEvent</span></strong>
{
    uint16 Category;
    string CategoryString;
    string ComputerName;
    uint8 Data[];
    uint16 EventCode;
    uint32 EventIdentifier;
    uint8 EventType;
    string InsertionStrings[];
    string Logfile;
    string Message;
    uint32 RecordNumber;
    string SourceName;
    datetime TimeGenerated;
    datetime TimeWritten;
    string Type;
    string User;
};

EventWatcher

.NET framework allow us to detect events as they occur.
The following example is detecting the __InstanceCreationEvent

<span style="color:#339966;">// initialization

// Create event query to be notified within 1 second of
// a change in a service</span>
EventQuery query = new EventQuery();
query.QueryString = "<span style="color:#ff0000;">SELECT * FROM</span>" +
    "<span style="color:#ff0000;"><strong> __InstanceCreationEvent </strong>WITHIN 1 </span>" +
    "<span style="color:#ff0000;">WHERE TargetInstance isa \"Win32_Process\"</span>";

<span style="color:#339966;">// Initialize an event watcher and subscribe to events
// that match this query</span>
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
// times out watcher.WaitForNextEvent in 20 seconds
watcher.Options.Timeout = new TimeSpan(0, 0, 20);

<span style="color:#339966;">// Block until the next event occurs
// Note: this can be done in a loop if waiting for
//        more than one occurrence</span>
Console.WriteLine("<span style="color:#ff0000;">Open an application (notepad.exe) to trigger an event.</span>");
ManagementBaseObject e = watcher.WaitForNextEvent();

<span style="color:#339966;">//Display information from the event</span>
Console.WriteLine(
    "<span style="color:#ff0000;">Process {0} has been created, path is: {1}</span>",
    ((ManagementBaseObject)e
    ["<span style="color:#ff0000;">TargetInstance</span>"])["Name"],
    ((ManagementBaseObject)e
    ["<span style="color:#ff0000;">TargetInstance</span>"])["ExecutablePath"]);

<span style="color:#339966;">//Cancel the subscription</span>
watcher.Stop();

Leave a comment