How to: Retrieve Information About Managed Objects by Queries

Queries for WMI data in .NET Framework can be specified as a string in the WMI supported WQL format, or constructed using a query class from the System.Management namespace. The WqlEventQuery class is used for event queries, and the WqlObjectQuery class is used for data queries.

Example

The following code example demonstrates how a query can be invoked using the ManagementObjectSearcher class. In this case, the SelectQuery class is used to specify a request for environment variables under the System user name. The query returns results in a collection.

Imports System.Management
Imports System

' This example demonstrates how to perform an object query.

Public Class QueryInstances

    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        'Create a query for system environment variables only
        Dim query As SelectQuery
        query = new SelectQuery("Win32_Environment", _
            "UserName = ""<system>""")

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

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

    End Function
End Class
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 (ManagementObject envVar in searcher.Get()) {
         Console.WriteLine("System environment variable {0} = {1}", 
            envVar["Name"], envVar["VariableValue"]);
      }
      return 0;
    }
}

Compiling the Code

The example requires references to the System and System.Management namespaces.

See Also

Tasks

How to: Retrieve Collections of Managed Objects

Concepts

WMI Queries

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.