Share via


Retrieving Collections of Management Objects

The following code example uses the System.Management collection classes to enumerate environment variables on a computer. Some parameters can be left to the default values in this example because the example gets information from the local computer. The example returns a collection of all objects for the specified class (Win32_Environment). Following the retrieval of the collection, the code enumerates through the collection, using the foreach statement, and displays the name and value of each variable in the collection. Developers familiar with the Scripting API for WMI will notice some similarities. Two different variations are shown: the first uses the ManagementObjectSearcher class, used with the simplest form of a query that represents essentially a full enumeration; the second gets the class object for Win32_Environment and uses the GetInstances() method to enumerate its instances.

using System;
using System.Management;

// This example demonstrates how to perform a synchronous instance enumeration.

public class EnumerateInstances {
    public static int Main(string[] args) {
      // Build a query for enumeration of Win32_Environment instances
      SelectQuery query = new SelectQuery("Win32_Environment");

      // Instantiate an object searcher with this query
      ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); 

      // Call Get() to retrieve the collection of objects and loop through it
      foreach (ManagementBaseObject envVar in searcher.Get())
         Console.WriteLine("Variable : {0}, Value = {1}", 
            envVar["Name"],envVar["VariableValue"]);
      return 0;
    }
}

[Visual Basic]
Imports System
Imports System.Management
' This example demonstrates how to perform a synchronous instance enumeration.

Public Class EnumerateInstances  
   Overloads Public Shared Function Main(args() As String) As Integer
      ' Build a query for enumeration of Win32_Environment instances
      Dim query As New SelectQuery("Win32_Environment")

      ' Instantiate an object searcher with this query
      Dim searcher As New ManagementObjectSearcher(query)

      ' Call Get() to retrieve the collection of objects and loop through it
      Dim envVar As ManagementBaseObject
      For Each envVar In  searcher.Get()
         Console.WriteLine("Variable : {0}, Value = {1}", _
            envVar("Name"), envVar("VariableValue"))
      Next envVar
      Return 0
   End Function 
End Class

Access to management information often occurs in distributed environments, and might involve large amounts of data. To support this, management operations can also be performed asynchronously. The next example shows how to enumerate all services on a computer in an asynchronous coding pattern. The method used to invoke an operation asynchronously is an overload of the synchronous method, taking an additional parameter of type ManagementOperationObserver for handling the callbacks for results. This object defines events for notification on results and completion, to which you subscribe handlers that execute when these events are raised.

using System;
using System.Management;

// This example demonstrates how to perform an asynchronous instance enumeration.

public class EnumerateInstancesAsync {
    public static int Main(string[] args) {
      //Enumerate asynchronously using Object Searcher
      //===============================================

      //Instantiate an object searcher with the query
      ManagementObjectSearcher searcher = 
         new ManagementObjectSearcher(new SelectQuery("Win32_Service")); 

      // Create a results watcher object, and handler for results and completion
      ManagementOperationObserver results = new ManagementOperationObserver();
      ObjectHandler objectHandler = new ObjectHandler();

      // Attach handler to events for results and completion
      results.ObjectReady += new ObjectReadyEventHandler(objectHandler.NewObject);
      results.Completed += new CompletedEventHandler(objectHandler.Done);

      //Call the asynchronous overload of Get() to start the enumeration
      searcher.Get(results);
         
      //Do something else while results arrive asynchronously
      while (!objectHandler.IsCompleted) {
         System.Threading.Thread.Sleep (1000);
      }

      objectHandler.Reset();
      return 0;
   }


   //Handler for asynchronous results
   public class ObjectHandler {
      private bool isCompleted = false;

      public void NewObject(object sender, ObjectReadyEventArgs obj) {
         Console.WriteLine("Service : {0}, State = {1}", 
            obj.NewObject["Name"], obj.NewObject["State"]);
      }

      public bool IsCompleted {
         get { 
            return isCompleted;
         }
      }
      
      public void Reset()   {
         isCompleted = false;
      }

      public void Done(object sender, CompletedEventArgs obj) {
         isCompleted = true;
      }
   }
}

See Also

Accessing Management Information with System.Management | Querying for Management Information | Subscribing to and Consuming Events | Executing Methods on Management Objects | Remoting and Connection Options | Using Strongly-typed Objects