共用方式為


查詢管理資訊

WMI 有一項非常有用的功能,即為根據給定的準則來查詢資料和擷取資訊子集。在分散式案例中,為求效率起見,查詢緊靠在資訊來源旁執行 (在產生資料的電腦上),並且透過線路只傳送結果。如需 WMI 查詢的詳細資訊,請參閱 MSDN 的 WMI 文件。

下列程式碼範例展示如何使用 ManagementObjectSearcher 類別叫用查詢。查詢可指定為支援 WQL 格式的 WMI 字串,或使用數個可用查詢類別的其中一個來建構。在這個範例中,SelectQuery 類別僅用來指定系統環境的要求。結果將於列舉集合中傳回。

using System;
using System.Management;

// This example demonstrates how to perform an object query.

public class QueryInstances {
    public static int Main(string[] args) {
      // Create a query for system environment variables only
      SelectQuery query = 
         new SelectQuery("Win32_Environment", "UserName=\"<SYSTEM>\"");

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

      // Get the resulting collection and loop through it
      foreach (ManagementBaseObject envVar in searcher.Get()) {
         Console.WriteLine("System environment variable {0} = {1}", 
            envVar["Name"], envVar["VariableValue"]);
      }
      return 0;
    }
}

[Visual Basic]
Imports System
Imports System.Management

' This example demonstrates how to perform an object query.

Public Class QueryInstances
   Overloads Public Shared Function Main(args() As String) As Integer
      ' Create a query for system environment variables only
      Dim query As _
         New SelectQuery("Win32_Environment", "UserName=""<SYSTEM>""")

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

      ' Get the resulting collection and loop through it
      Dim envVar As ManagementBaseObject
      For Each envVar In  searcher.Get()
       Console.WriteLine("System environment variable {0} = {1}", _
          envVar("Name"), envVar("VariableValue"))
      Next envVar
      Return 0
   End Function 
End Class

請參閱

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