共用方式為


擷取管理物件集合

下列程式碼範例使用 System.Management 集合類別列舉電腦的環境變數。由於這個範例是從本機電腦取得資訊,因此某些參數可保留為預設值。這個範例將傳回指定類別 (Win32_Environment) 的所有物件集合。取出集合後,程式碼使用 foreach 陳述式列舉集合,並顯示集合中的所有變數名稱和值。熟悉 Scripting API for WMI 的開發人員將會發現兩者的相似處。以下說明兩種不同處:第一個使用 ManagementObjectSearcher 類別,搭配使用最簡單的查詢格式來表示完整的列舉型別;第二個取得 Win32_Environment 的類別物件並使用 GetInstances() 方法來列舉其執行個體。

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

分散式環境中經常會發生存取管理資訊,因此可能含有大量資料。您也可以非同步執行管理作業來支援大量資料。下一個範例說明如何使用非同步程式碼撰寫模式來列舉電腦的所有服務。用來非同步叫用作業的方法是同步方法的多載,使用其他的參數型別 ManagementOperationObserver 來處理結果的回呼 (Callback)。這個物件定義結果和完成的事件告知,您可以訂閱引發這些事件時所執行的處理常式。

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;
      }
   }
}

請參閱

使用 System.Management 存取管理資訊 | 查詢管理資訊 | 訂閱和使用事件 | 執行管理物件上的方法 | 遠端和連接選項 | 使用強式型別物件