System.Management
Describes the possible text formats that can be used with .
Managed Object Format
XML DTD that corresponds to CIM DTD version 2.0
XML WMI DTD that corresponds to CIM DTD version 2.0.
Using this value enables a few WMI-specific extensions, like embedded objects.
Describes the possible CIM types for properties, qualifiers, or method parameters.
Invalid Type
A signed 8-bit integer.
An unsigned 8-bit integer.
A signed 16-bit integer.
An unsigned 16-bit integer.
A signed 32-bit integer.
An unsigned 32-bit integer.
A signed 64-bit integer.
An unsigned 64-bit integer.
A floating-point 32-bit number.
A floating point 64-bit number.
A boolean.
A string.
A date or time value, represented in a string in DMTF
date/time format: yyyymmddHHMMSS.mmmmmmsUUU
where:
yyyymmdd - is the date in year/month/day
HHMMSS - is the time in hours/minutes/seconds
mmmmmm - is the number of microseconds in 6 digits
sUUU - is a sign (+ or -) and a 3-digit UTC offset
A reference to another object. This is represented by a
string containing the path to the referenced object
A 16-bit character.
An embedded object.
Note that embedded objects differ from references in that the embedded object
doesn't have a path and its lifetime is identical to the lifetime of the
containing object.
Describes the object comparison modes that can be used with .
Note that these values may be combined.
A mode that compares all elements of the compared objects.
A mode that compares the objects, ignoring qualifiers.
A mode that ignores the source of the objects, namely the server
and the namespace they came from, in comparison to other objects.
A mode that ignores the default values of properties.
This value is only meaningful when comparing classes.
A mode that assumes that the objects being compared are instances of
the same class. Consequently, this value causes comparison
of instance-related information only. Use this flag to optimize
performance. If the objects are not of the same class, the results are undefined.
A mode that compares string values in a case-insensitive
manner. This applies to strings and to qualifier values. Property and qualifier
names are always compared in a case-insensitive manner whether this flag is
specified or not.
A mode that ignores qualifier flavors. This flag still takes
qualifier values into account, but ignores flavor distinctions such as
propagation rules and override restrictions.
Contains the basic elements of a management
object. It serves as a base class to more specific management object classes.
Initializes a new instance of the class that is serializable.
The to populate with data.
The destination (see ) for this serialization.
Provides the internal WMI object represented by a ManagementObject.
See remarks with regard to usage.
The that references the requested WMI object.
An representing the internal WMI object.
This operator is used internally by instrumentation code. It is not intended
for direct use by regular client or instrumented applications.
Factory for various types of base object
IWbemClassObject
The scope
Returns a copy of the object.
The new cloned object.
Gets or sets a collection of objects describing the properties of the
management object.
A that represents the
properties of the management object.
Gets or sets the collection of WMI system properties of the management object (for example, the
class name, server, and namespace). WMI system property names begin with
"__".
A that represents the system properties of the management object.
Gets or sets the collection of objects defined on the management object.
Each element in the collection holds information such as the qualifier name,
value, and flavor.
A that represents the qualifiers
defined on the management object.
Gets or sets the path to the management object's class.
A that represents the path to the management object's class.
For example, for the \\MyBox\root\cimv2:Win32_LogicalDisk=
'C:' object, the class path is \\MyBox\root\cimv2:Win32_LogicalDisk
.
Gets access to property values through [] notation.
The name of the property of interest.
An containing the
value of the requested property.
Gets an equivalent accessor to a property's value.
The name of the property of interest.
The value of the specified property.
Gets the value of the specified qualifier.
The name of the qualifier of interest.
The value of the specified qualifier.
Sets the value of the named qualifier.
The name of the qualifier to set. This parameter cannot be null.
The value to set.
Returns the value of the specified property qualifier.
The name of the property to which the qualifier belongs.
The name of the property qualifier of interest.
The value of the specified qualifier.
Sets the value of the specified property qualifier.
The name of the property to which the qualifier belongs.
The name of the property qualifier of interest.
The new value for the qualifier.
Returns a textual representation of the object in the specified format.
The requested textual format.
The textual representation of the
object in the specified format.
Compares two management objects.
An object to compare with this instance.
if
is an instance of and represents
the same object as this instance; otherwise, .
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
The hash code for ManagementBaseObjects is based on the MOF for the WbemObject that this instance is based on. Two different ManagementBaseObject instances pointing to the same WbemObject in WMI will have the same mof and thus the same hash code. Changing a property value of an object will change the hash code.
A hash code for the current object.
Compares this object to another, based on specified options.
The object to which to compare this object.
Options on how to compare the objects.
if the objects compared are equal
according to the given options; otherwise,
.
Sets the value of the named property.
The name of the property to be changed.
The new value for this property.
Represents a CIM management class from WMI. CIM (Common Information Model) classes
represent management information including hardware, software, processes, etc.
For more information about the CIM classes available in Windows search for "win32 classes".
using System;
using System.Management;
// This example demonstrates getting information about a class using the ManagementClass object
class Sample_ManagementClass
{
public static int Main(string[] args) {
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
diskClass.Get();
Console.WriteLine("Logical Disk class has " + diskClass.Properties.Count + " properties");
return 0;
}
}
Imports System
Imports System.Management
' This example demonstrates getting information about a class using the ManagementClass object
Class Sample_ManagementClass
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("Win32_LogicalDisk")
diskClass.Get()
Console.WriteLine(("Logical Disk class has " & _
diskClass.Properties.Count.ToString() & _
" properties"))
Return 0
End Function
End Class
Internal factory for classes, used when deriving a class
or cloning a class. For these purposes we always mark
the class as "bound".
The underlying WMI object
Seed class from which we will get initialization info
Initializes a new instance
of the class.
Initializes a new instance of the class. This is the
default constructor.
ManagementClass c = new ManagementClass();
Dim c As New ManagementClass()
Initializes a new instance of the class initialized to the
given path.
A specifying which WMI class to bind to.
The parameter must specify a WMI class
path.
ManagementClass c = new ManagementClass(
new ManagementPath("Win32_LogicalDisk"));
Dim c As New ManagementClass( _
New ManagementPath("Win32_LogicalDisk"))
Initializes a new instance of the class initialized to the given path.
The path to the WMI class.
ManagementClass c = new
ManagementClass("Win32_LogicalDisk");
Dim c As New ManagementClass("Win32_LogicalDisk")
Initializes a new instance of the class initialized to the
given WMI class path using the specified options.
A representing the WMI class path.
An representing the options to use when retrieving this class.
ManagementPath p = new ManagementPath("Win32_Process");
//Options specify that amended qualifiers are to be retrieved along with the class
ObjectGetOptions o = new ObjectGetOptions(null, true);
ManagementClass c = new ManagementClass(p,o);
Dim p As New ManagementPath("Win32_Process")
' Options specify that amended qualifiers are to be retrieved along with the class
Dim o As New ObjectGetOptions(Null, True)
Dim c As New ManagementClass(p,o)
Initializes a new instance of the class initialized to the given WMI class path
using the specified options.
The path to the WMI class.
An representing the options to use when retrieving the WMI class.
//Options specify that amended qualifiers should be retrieved along with the class
ObjectGetOptions o = new ObjectGetOptions(null, true);
ManagementClass c = new ManagementClass("Win32_ComputerSystem",o);
' Options specify that amended qualifiers should be retrieved along with the class
Dim o As New ObjectGetOptions(Null, True)
Dim c As New ManagementClass("Win32_ComputerSystem",o)
Initializes a new instance of the class for the specified
WMI class in the specified scope and with the specified options.
A that specifies the scope (server and namespace) where the WMI class resides.
A that represents the path to the WMI class in the specified scope.
An that specifies the options to use when retrieving the WMI class.
The path can be specified as a full
path (including server and namespace). However, if a scope is specified, it will
override the first portion of the full path.
ManagementScope s = new ManagementScope("\\\\MyBox\\root\\cimv2");
ManagementPath p = new ManagementPath("Win32_Environment");
ObjectGetOptions o = new ObjectGetOptions(null, true);
ManagementClass c = new ManagementClass(s, p, o);
Dim s As New ManagementScope("\\MyBox\root\cimv2")
Dim p As New ManagementPath("Win32_Environment")
Dim o As New ObjectGetOptions(Null, True)
Dim c As New ManagementClass(s, p, o)
Initializes a new instance of the class for the specified WMI class, in the
specified scope, and with the specified options.
The scope in which the WMI class resides.
The path to the WMI class within the specified scope.
An that specifies the options to use when retrieving the WMI class.
The path can be specified as a full
path (including server and namespace). However, if a scope is specified, it will
override the first portion of the full path.
ManagementClass c = new ManagementClass("\\\\MyBox\\root\\cimv2",
"Win32_Environment",
new ObjectGetOptions(null, true));
Dim c As New ManagementClass("\\MyBox\root\cimv2", _
"Win32_Environment", _
new ObjectGetOptions(Null, True))
Gets or sets the path of the WMI class to
which the
object is bound.
The path of the object's class.
When the property is set to a new value,
the
object will be
disconnected from any previously-bound WMI class. Reconnect to the new WMI class path.
ManagementClass c = new ManagementClass();
c.Path = "Win32_Environment";
Dim c As New ManagementClass()
c.Path = "Win32_Environment"
Gets or sets an array containing all WMI classes in the
inheritance hierarchy from this class to the top.
A string collection containing the
names of all WMI classes in the inheritance hierarchy of this class.
This property is read-only.
ManagementClass c = new ManagementClass("Win32_LogicalDisk");
foreach (string s in c.Derivation)
Console.WriteLine("Further derived from : ", s);
Dim c As New ManagementClass("Win32_LogicalDisk")
Dim s As String
For Each s In c.Derivation
Console.WriteLine("Further derived from : " & s)
Next s
Gets or sets a collection of objects that
represent the methods defined in the WMI class.
A representing the methods defined in the WMI class.
ManagementClass c = new ManagementClass("Win32_Process");
foreach (Method m in c.Methods)
Console.WriteLine("This class contains this method : ", m.Name);
Dim c As New ManagementClass("Win32_Process")
Dim m As Method
For Each m in c.Methods
Console.WriteLine("This class contains this method : " & m.Name)
Returns the collection of
all instances of the class.
Returns the collection of all instances of the class.
A collection of the objects
representing the instances of the class.
ManagementClass c = new ManagementClass("Win32_Process");
foreach (ManagementObject o in c.GetInstances())
Console.WriteLine("Next instance of Win32_Process : ", o.Path);
Dim c As New ManagementClass("Win32_Process")
Dim o As ManagementObject
For Each o In c.GetInstances()
Console.WriteLine("Next instance of Win32_Process : " & o.Path)
Next o
Returns the collection of all instances of the class using the specified options.
The additional operation options.
A collection of the objects
representing the instances of the class, according to the specified options.
EnumerationOptions opt = new EnumerationOptions();
//Will enumerate instances of the given class and any subclasses.
o.enumerateDeep = true;
ManagementClass c = new ManagementClass("CIM_Service");
foreach (ManagementObject o in c.GetInstances(opt))
Console.WriteLine(o["Name"]);
Dim opt As New EnumerationOptions()
'Will enumerate instances of the given class and any subclasses.
o.enumerateDeep = True
Dim c As New ManagementClass("CIM_Service")
Dim o As ManagementObject
For Each o In c.GetInstances(opt)
Console.WriteLine(o["Name"])
Next o
Returns the collection of all instances of the class, asynchronously.
The object to handle the asynchronous operation's progress.
ManagementClass c = new ManagementClass("Win32_Share");
MyHandler h = new MyHandler();
ManagementOperationObserver ob = new ManagementOperationObserver();
ob.ObjectReady += new ObjectReadyEventHandler (h.NewObject);
ob.Completed += new CompletedEventHandler (h.Done);
c.GetInstances(ob);
while (!h.Completed)
System.Threading.Thread.Sleep (1000);
//Here you can use the object
Console.WriteLine(o["SomeProperty"]);
public class MyHandler
{
private bool completed = false;
public void NewObject(object sender, ObjectReadyEventArgs e) {
Console.WriteLine("New result arrived !", ((ManagementObject)(e.NewObject))["Name"]);
}
public void Done(object sender, CompletedEventArgs e) {
Console.WriteLine("async Get completed !");
completed = true;
}
public bool Completed {
get {
return completed;
}
}
}
Dim c As New ManagementClass("Win32_Share")
Dim h As New MyHandler()
Dim ob As New ManagementOperationObserver()
ob.ObjectReady += New ObjectReadyEventHandler(h.NewObject)
ob.Completed += New CompletedEventHandler(h.Done)
c.GetInstances(ob)
While Not h.Completed
System.Threading.Thread.Sleep(1000)
End While
'Here you can use the object
Console.WriteLine(o("SomeProperty"))
Public Class MyHandler
Private completed As Boolean = false
Public Sub Done(sender As Object, e As EventArrivedEventArgs)
Console.WriteLine("async Get completed !")
completed = True
End Sub
Public ReadOnly Property Completed() As Boolean
Get
Return completed
End Get
End Property
End Class
Returns the collection of all instances of the class, asynchronously, using
the specified options.
The object to handle the asynchronous operation's progress.
The specified additional options for getting the instances.
Returns the collection of
all derived classes for the class.
Returns the collection of all subclasses for the class.
A collection of the objects that
represent the subclasses of the WMI class.
Retrieves the subclasses of the class using the specified
options.
The specified additional options for retrieving subclasses of the class.
A collection of the objects
representing the subclasses of the WMI class, according to the specified
options.
EnumerationOptions opt = new EnumerationOptions();
//Causes return of deep subclasses as opposed to only immediate ones.
opt.enumerateDeep = true;
ManagementObjectCollection c = (new
ManagementClass("Win32_Share")).GetSubclasses(opt);
Dim opt As New EnumerationOptions()
'Causes return of deep subclasses as opposed to only immediate ones.
opt.enumerateDeep = true
Dim cls As New ManagementClass("Win32_Share")
Dim c As ManagementObjectCollection
c = cls.GetSubClasses(opt)
Returns the collection of all classes derived from this class, asynchronously.
The object to handle the asynchronous operation's progress.
Retrieves all classes derived from this class, asynchronously, using the specified
options.
The object to handle the asynchronous operation's progress.
The specified additional options to use in the derived class retrieval.
Derives a new class from this class.
The name of the new class to be derived.
A new
that represents a new WMI class derived from the original class.
Note that the newly returned class has not been committed
until the method is explicitly called.
ManagementClass existingClass = new ManagementClass("CIM_Service");
ManagementClass newClass = existingClass.Derive("My_Service");
newClass.Put(); //to commit the new class to the WMI repository.
Dim existingClass As New ManagementClass("CIM_Service")
Dim newClass As ManagementClass
newClass = existingClass.Derive("My_Service")
newClass.Put() 'to commit the new class to the WMI repository.
Creates a new instance of the WMI class.
A that represents a new
instance of the WMI class.
Note that the new instance is not committed until the
method is called. Before committing it, the key properties must
be specified.
ManagementClass envClass = new ManagementClass("Win32_Environment");
ManagementObject newInstance =
existingClass.CreateInstance("My_Service");
newInstance["Name"] = "Cori";
newInstance.Put(); //to commit the new instance.
Dim envClass As New ManagementClass("Win32_Environment")
Dim newInstance As ManagementObject
newInstance = existingClass.CreateInstance("My_Service")
newInstance("Name") = "Cori"
newInstance.Put() 'to commit the new instance.
Returns a copy of the object.
The cloned
object.
Note that this does not create a copy of the
WMI class; only an additional representation is created.
Retrieves classes related
to the WMI class.
Retrieves classes related to the WMI class.
A collection of the or
objects that represents WMI classes or instances related to
the WMI class.
The method queries the WMI schema for all
possible associations that the WMI class may have with other classes, or in rare
cases, to instances.
ManagementClass c = new ManagementClass("Win32_LogicalDisk");
foreach (ManagementClass r in c.GetRelatedClasses())
Console.WriteLine("Instances of {0} may have
relationships to this class", r["__CLASS"]);
Dim c As New ManagementClass("Win32_LogicalDisk")
Dim r As ManagementClass
For Each r In c.GetRelatedClasses()
Console.WriteLine("Instances of {0} may have relationships _
to this class", r("__CLASS"))
Next r
Retrieves classes related to the WMI class.
The class from which resulting classes have to be derived.
A collection of classes related to
this class.
Retrieves classes related to the WMI class based on the specified
options.
The class from which resulting classes have to be derived.
The relationship type which resulting classes must have with the source class.
This qualifier must be present on the relationship.
This qualifier must be present on the resulting classes.
The resulting classes must have this role in the relationship.
The source class must have this role in the relationship.
The options for retrieving the resulting classes.
A collection of classes related to
this class.
Retrieves classes
related to the WMI class, asynchronously.
The object to handle the asynchronous operation's progress.
Retrieves classes related to the WMI class, asynchronously, given the related
class name.
The object to handle the asynchronous operation's progress.
The name of the related class.
Retrieves classes related to the
WMI class, asynchronously, using the specified options.
Handler for progress and results of the asynchronous operation.
The class from which resulting classes have to be derived.
The relationship type which resulting classes must have with the source class.
This qualifier must be present on the relationship.
This qualifier must be present on the resulting classes.
The resulting classes must have this role in the relationship.
The source class must have this role in the relationship.
The options for retrieving the resulting classes.
Retrieves relationship
classes that relate the class to others.
Retrieves relationship classes that relate the class to others.
A collection of association classes
that relate the class to any other class.
Retrieves relationship classes that relate the class to others, where the
endpoint class is the specified class.
The endpoint class for all relationship classes returned.
A collection of association classes
that relate the class to the specified class.
Retrieves relationship classes that relate this class to others, according to
specified options.
All resulting relationship classes must derive from this class.
Resulting relationship classes must have this qualifier.
The source class must have this role in the resulting relationship classes.
Specifies options for retrieving the results.
A collection of association classes
that relate this class to others, according to the specified options.
Retrieves relationship classes that relate the class to others,
asynchronously.
The object to handle the asynchronous operation's progress.
Retrieves relationship classes that relate the class to the specified WMI class,
asynchronously.
The object to handle the asynchronous operation's progress.
The WMI class to which all returned relationships should point.
Retrieves relationship classes that relate the class according to the specified
options, asynchronously.
The handler for progress and results of the asynchronous operation.
The class from which all resulting relationship classes must derive.
The qualifier which the resulting relationship classes must have.
The role which the source class must have in the resulting relationship classes.
The options for retrieving the results.
Generates a strongly-typed class for a given WMI class.
Generates a strongly-typed class for a given WMI class.
if the class for managing system properties must be included; otherwise, .
if the generated class will manage system properties; otherwise, .
A instance
representing the declaration for the strongly-typed class.
using System;
using System.Management;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
void GenerateCSharpCode()
{
string strFilePath = "C:\\temp\\LogicalDisk.cs";
CodeTypeDeclaration ClsDom;
ManagementClass cls1 = new ManagementClass(null,"Win32_LogicalDisk",null);
ClsDom = cls1.GetStronglyTypedClassCode(false,false);
ICodeGenerator cg = (new CSharpCodeProvider()).CreateGenerator ();
CodeNamespace cn = new CodeNamespace("TestNamespace");
// Add any imports to the code
cn.Imports.Add (new CodeNamespaceImport("System"));
cn.Imports.Add (new CodeNamespaceImport("System.ComponentModel"));
cn.Imports.Add (new CodeNamespaceImport("System.Management"));
cn.Imports.Add(new CodeNamespaceImport("System.Collections"));
// Add class to the namespace
cn.Types.Add (ClsDom);
//Now create the filestream (output file)
TextWriter tw = new StreamWriter(new
FileStream (strFilePath,FileMode.Create));
// And write it to the file
cg.GenerateCodeFromNamespace (cn, tw, new CodeGeneratorOptions());
tw.Close();
}
Generates a strongly-typed class for a given WMI class. This function generates code for Visual Basic,
C#, or JScript, depending on the input parameters.
The language of the code to be generated.
The path of the file where the code is to be written.
The .NET namespace into which the class should be generated. If this is empty, the namespace will be generated from the WMI namespace.
, if the method succeeded;
otherwise, .
using System;
using System.Management;
ManagementClass cls = new ManagementClass(null,"Win32_LogicalDisk",null,"");
cls.GetStronglyTypedClassCode(CodeLanguage.CSharp,"C:\temp\Logicaldisk.cs",String.Empty);
Provides methods to convert DMTF datetime and time interval to CLR compliant
and format and vice versa.
using System;
using System.Management;
// The sample below demonstrates the various conversions that can be done using ManagementDateTimeConverter class
class Sample_ManagementDateTimeConverterClass
{
public static int Main(string[] args)
{
string dmtfDate = "20020408141835.999999-420";
string dmtfTimeInterval = "00000010122532:123456:000";
// Converting DMTF datetime to System.DateTime
DateTime dt = ManagementDateTimeConverter.ToDateTime(dmtfDate);
// Converting System.DateTime to DMTF datetime
string dmtfDate = ManagementDateTimeConverter.ToDateTime(DateTime.Now);
// Converting DMTF timeinterval to System.TimeSpan
System.TimeSpan tsRet = ManagementDateTimeConverter. ToTimeSpan(dmtfTimeInterval);
//Converting System.TimeSpan to DMTF time interval format
System.TimeSpan ts = new System.TimeSpan(10,12,25,32,456);
string dmtfTimeInt = ManagementDateTimeConverter.ToDmtfTimeInterval(ts);
return 0;
}
}
Imports System
Imports System.Management
'The sample below demonstrates the various conversions that can be done using ManagementDateTimeConverter class
Class Sample_ManagementClass
Overloads Public Shared Function Main(args() As String) As Integer
Dim dmtfDate As String = "20020408141835.999999-420"
Dim dmtfTimeInterval As String = "00000010122532:123456:000"
'Converting DMTF datetime and intervals to System.DateTime
Dim dt As DateTime = ManagementDateTimeConverter.ToDateTime(dmtfDate)
'Converting System.DateTime to DMTF datetime
dmtfDate = ManagementDateTimeConverter.ToDateTime(DateTime.Now)
' Converting DMTF timeinterval to System.TimeSpan
Dim tsRet As System.TimeSpan = ManagementDateTimeConverter.ToTimeSpan(dmtfTimeInterval)
'Converting System.TimeSpan to DMTF time interval format
Dim ts As System.TimeSpan = New System.TimeSpan(10, 12, 25, 32, 456)
String dmtfTimeInt = ManagementDateTimeConverter.ToDmtfTimeInterval(ts)
Return 0
End Function
End Class
Converts a given DMTF datetime to object. The returned DateTime will be in the
current TimeZone of the system.
A string representing the datetime in DMTF format.
A object that represents the given DMTF datetime.
Date and time in WMI is represented in DMTF datetime format. This format is explained in WMI SDK documentation.
DMTF datetime string has an UTC offset which this datetime string represents.
During conversion to , UTC offset is used to convert the date to the
current timezone. According to DMTF format a particular field can be represented by the character
'*'. This will be converted to the MinValue of this field that can be represented in .
// Convert a DMTF datetime to System.DateTime
DateTime date = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420");
' Convert a DMTF datetime to System.DateTime
Dim date as DateTime = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420")
Converts a given object to DMTF format.
A object representing the datetime to be converted to DMTF datetime.
A string that represents the DMTF datetime for the given DateTime object.
Date and time in WMI is represented in DMTF datetime format. This format is explained in WMI SDK documentation.
The DMTF datetime string represented will be with respect to the UTC offset of the
current timezone. The lowest precision in DMTF is microseconds and
in is Ticks , which is equivalent to 100 of nanoseconds.
During conversion these Ticks are converted to microseconds and rounded
off to the nearest microsecond.
// Convert the current time in System.DateTime to DMTF format
string dmtfDateTime = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now);
' Convert the current time in System.DateTime to DMTF format
Dim dmtfDateTime as String = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now)
Converts a given DMTF time interval to object.
A string represesentation of the DMTF time interval.
A object that represents the given DMTF time interval.
Time interval in WMI is represented in DMTF format. This format is explained in WMI SDK documentation.
If the DMTF time interval value is more than that of
then is thrown.
// Convert a DMTF time interval to System.TimeSpan
TimeSpan dmtfTimeInterval = ManagementDateTimeConverter.ToTimeSpan("00000010122532:123456:000");
' Convert a DMTF time interval to System.TimeSpan
Dim ts as TimeSpan = ManagementDateTimeConverter.ToTimeSpan("00000010122532:123456:000")
Converts a given object to DMTF time interval.
A object representing the datetime to be converted to DMTF time interval.
A string that represents the DMTF time interval for the given TimeSpan object.
Time interval in WMI is represented in DMTF datetime format. This format
is explained in WMI SDK documentation. The lowest precision in
DMTF is microseconds and in is Ticks , which is equivalent
to 100 of nanoseconds.During conversion these Ticks are converted to
microseconds and rounded off to the nearest microsecond.
// Construct a Timespan object and convert it to DMTF format
System.TimeSpan ts = new System.TimeSpan(10,12,25,32,456);
String dmtfTimeInterval = ManagementDateTimeConverter.ToDmtfTimeInterval(ts);
// Construct a Timespan object and convert it to DMTF format
Dim ts as System.TimeSpan = new System.TimeSpan(10,12,25,32,456)
Dim dmtfTimeInterval as String = ManagementDateTimeConverter.ToDmtfTimeInterval(ts)
Represents the virtual base class to hold event data for WMI events.
Constructor. This is not callable directly by applications.
The operation context which is echoed back
from the operation which trigerred the event.
Gets the operation context echoed back
from the operation that triggered the event.
A WMI context object containing
context information provided by the operation that triggered the event.
Holds event data for the event.
Constructor.
The operation context which is echoed back
from the operation which triggerred the event.
The newly arrived WmiObject.
Gets the newly-returned object.
A representing the
newly-returned object.
Holds event data for the event.
Constructor.
The operation context which is echoed back
from the operation which trigerred the event.
The completion status of the operation.
Additional status information
encapsulated within a WmiObject. This may be null.
Gets or sets additional status information
within a WMI object. This may be null.
if an error did not occur. Otherwise, may be non-null if the provider
supports extended error information.
Gets the completion status of the operation.
A value
indicating the return code of the operation.
Holds event data for the event.
Constructor
The operation context which is echoed back
from the operation which trigerred the event.
The WmiPath representing the identity of the
object that has been put.
Gets the identity of the
object that has been put.
A containing the path of the object that has
been put.
Holds event data for the event.
Constructor
The operation context which is echoed back
from the operation which trigerred the event.
A quantity representing the total
amount of work required to be done by the operation.
A quantity representing the current
amount of work required to be done by the operation. This is
always less than or equal to upperBound.
Optional additional information regarding
operation progress.
Gets the total
amount of work required to be done by the operation.
An integer representing the total
amount of work for the operation.
Gets the current amount of work
done by the operation. This is always less than or equal to .
An integer representing the current amount of work
already completed by the operation.
Gets or sets optional additional information regarding the operation's progress.
A string containing additional
information regarding the operation's progress.
Holds event data for the event.
Gets the WMI event that was delivered.
The object representing the WMI event.
Holds event data for the event.
Gets the completion status of the operation.
A value representing the status of the
operation.
Represents the method that will handle the event.
Represents the method that will handle the event.
Subscribes to temporary event notifications
based on a specified event query.
using System;
using System.Management;
// This example demonstrates how to subscribe to an event using the ManagementEventWatcher object.
class Sample_ManagementEventWatcher
{
public static int Main(string[] args) {
//For the example, we'll put a class into the repository, and watch
//for class deletion events when the class is deleted.
ManagementClass newClass = new ManagementClass();
newClass["__CLASS"] = "TestDeletionClass";
newClass.Put();
//Set up an event watcher and a handler for the event
ManagementEventWatcher watcher = new ManagementEventWatcher(
new WqlEventQuery("__ClassDeletionEvent"));
MyHandler handler = new MyHandler();
watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
//Start watching for events
watcher.Start();
// For the purpose of this sample, we delete the class to trigger the event
// and wait for two seconds before terminating the consumer
newClass.Delete();
System.Threading.Thread.Sleep(2000);
//Stop watching
watcher.Stop();
return 0;
}
public class MyHandler {
public void Arrived(object sender, EventArrivedEventArgs e) {
Console.WriteLine("Class Deleted = " +
((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]);
}
}
}
Imports System
Imports System.Management
' This example demonstrates how to subscribe an event using the ManagementEventWatcher object.
Class Sample_ManagementEventWatcher
Public Shared Sub Main()
' For the example, we'll put a class into the repository, and watch
' for class deletion events when the class is deleted.
Dim newClass As New ManagementClass()
newClass("__CLASS") = "TestDeletionClass"
newClass.Put()
' Set up an event watcher and a handler for the event
Dim watcher As _
New ManagementEventWatcher(New WqlEventQuery("__ClassDeletionEvent"))
Dim handler As New MyHandler()
AddHandler watcher.EventArrived, AddressOf handler.Arrived
' Start watching for events
watcher.Start()
' For the purpose of this sample, we delete the class to trigger the event
' and wait for two seconds before terminating the consumer
newClass.Delete()
System.Threading.Thread.Sleep(2000)
' Stop watching
watcher.Stop()
End Sub
Public Class MyHandler
Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
Console.WriteLine("Class Deleted = " & _
CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS"))
End Sub
End Class
End Class
Initializes a new instance of the class.
Initializes a new instance of the class. For further
initialization, set the properties on the object. This is the default constructor.
Initializes a new instance of the class when given a WMI event query.
An object representing a WMI event query, which determines the events for which the watcher will listen.
The namespace in which the watcher will be listening for
events is the default namespace that is currently set.
Initializes a new instance of the class when given a WMI event query in the
form of a string.
A WMI event query, which defines the events for which the watcher will listen.
The namespace in which the watcher will be listening for
events is the default namespace that is currently set.
Initializes a new instance of the
class that listens for events conforming to the given WMI event query.
A object representing the scope (namespace) in which the watcher will listen for events.
An object representing a WMI event query, which determines the events for which the watcher will listen.
Initializes a new instance of the
class that listens for events conforming to the given WMI event query. For this
variant, the query and the scope are specified as strings.
The management scope (namespace) in which the watcher will listen for events.
The query that defines the events for which the watcher will listen.
Initializes a new instance of the class that listens for
events conforming to the given WMI event query, according to the specified options. For
this variant, the query and the scope are specified as strings. The options
object can specify options such as a timeout and context information.
The management scope (namespace) in which the watcher will listen for events.
The query that defines the events for which the watcher will listen.
An object representing additional options used to watch for events.
Initializes a new instance of the class
that listens for events conforming to the given WMI event query, according to the specified
options. For this variant, the query and the scope are specified objects. The
options object can specify options such as timeout and context information.
A object representing the scope (namespace) in which the watcher will listen for events.
An object representing a WMI event query, which determines the events for which the watcher will listen.
An object representing additional options used to watch for events.
Ensures that outstanding calls are cleared. This is the destructor for the object.
Occurs when a new event arrives.
Occurs when a subscription is canceled.
Gets or sets the scope in which to watch for events (namespace or scope).
The scope in which to watch for events (namespace or scope).
Gets or sets the criteria to apply to events.
The criteria to apply to the events, which is equal to the event query.
Gets or sets the options used to watch for events.
The options used to watch for events.
Waits for the next event that matches the specified query to arrive, and
then returns it.
A representing the
newly arrived event.
If the event watcher object contains options with
a specified timeout, the API will wait for the next event only for the specified
amount of time; otherwise, the API will be blocked until the next event occurs.
Subscribes to events with the given query and delivers
them, asynchronously, through the event.
Cancels the subscription whether it is synchronous or asynchronous.
Represents the enumeration of all WMI error codes that are currently defined.
The operation was successful.
This value is returned when no more objects
are available, the number of objects returned is less than the number requested,
or at the end of an enumeration. It is also returned when the method is called
with a value of 0 for the "uCount" parameter.
An overridden property was deleted. This value is
returned to signal that the original, non-overridden value has been restored as a
result of the deletion.
The compared items (such as objects and classes)
are not identical.
A call timed out. This is not an
error condition; therefore, some results may have been returned.
No more data is available from the enumeration; the
user should terminate the enumeration.
The operation was
canceled.
A request is still in progress; however, the results are not
yet available.
More than one copy of the same object was detected in
the result set of an enumeration.
The user did not receive all of the requested objects
because of inaccessible resources (other than security violations).
The call failed.
The object could not be found.
The current user does not have permission to perform the
action.
The provider failed after
initialization.
A type mismatch occurred.
There was not enough memory for the operation.
The context object is not valid.
One of the parameters to the call is not correct.
The resource, typically a remote server, is not
currently available.
An internal, critical, and unexpected error occurred.
Report this error to Microsoft Product Support Services.
One or more network packets were corrupted during a remote session.
The feature or operation is not supported.
The specified base class is not valid.
The specified namespace could not be found.
The specified instance is not valid.
The specified class is not valid.
A provider referenced in the schema does not have a
corresponding registration.
A provider referenced in the schema has an incorrect or
incomplete registration.
COM cannot locate a provider referenced in the schema.
A component, such as a provider, failed to initialize for internal reasons.
A networking error that prevents normal operation has
occurred.
The requested operation is not valid. This error usually
applies to invalid attempts to delete classes or properties.
The query was not syntactically valid.
The requested query language is not supported.
In a put operation, the
flag was specified, but the instance already exists.
The add operation cannot be performed on the qualifier
because the owning object does not permit overrides.
The user attempted to delete a qualifier that was not
owned. The qualifier was inherited from a parent class.
The user attempted to delete a property that was not
owned. The property was inherited from a parent class.
The client made an unexpected and illegal sequence of
calls.
The user requested an illegal operation, such as
spawning a class from an instance.
There was an illegal attempt to specify a key qualifier
on a property that cannot be a key. The keys are specified in the class
definition for an object and cannot be altered on a per-instance basis.
The current object is not a valid class definition.
Either it is incomplete, or it has not been registered with WMI using
().
Reserved for future use.
Reserved for future use.
The property that you are attempting to modify is read-only.
The provider cannot perform the requested operation, such
as requesting a query that is too complex, retrieving an instance, creating or
updating a class, deleting a class, or enumerating a class.
An attempt was made to make a change that would
invalidate a derived class.
An attempt has been made to delete or modify a class that
has instances.
Reserved for future use.
A value of null was specified for a property that may
not be null, such as one that is marked by a , , or
qualifier.
The value provided for a qualifier was not a
legal qualifier type.
The CIM type specified for a property is not valid.
The request was made with an out-of-range value, or is
incompatible with the type.
An illegal attempt was made to make a class singleton,
such as when the class is derived from a non-singleton class.
The CIM type specified is not valid.
The requested method is not available.
The parameters provided for the method are not valid.
There was an attempt to get qualifiers on a system
property.
The property type is not recognized.
An asynchronous process has been canceled internally or
by the user. Note that because of the timing and nature of the asynchronous
operation, the operation may not have been truly canceled.
The user has requested an operation while WMI is in the
process of quitting.
An attempt was made to reuse an existing method name from
a base class, and the signatures did not match.
One or more parameter values, such as a query text, is
too complex or unsupported. WMI is requested to retry the operation
with simpler parameters.
A parameter was missing from the method call.
A method parameter has an invalid qualifier.
One or more of the method parameters have
qualifiers that are out of sequence.
The return value for a method has an qualifier.
The specified object path was invalid.
There is not enough free disk space to continue the
operation.
The supplied buffer was too small to hold all the objects
in the enumerator or to read a string property.
The provider does not support the requested put
operation.
An object with an incorrect type or version was
encountered during marshaling.
A packet with an incorrect type or version was
encountered during marshaling.
The packet has an unsupported version.
The packet is corrupted.
An attempt has been made to mismatch qualifiers, such as
putting [key] on an object instead of a property.
A duplicate parameter has been declared in a CIM method.
Reserved for future use.
The delivery of an event has failed. The provider may
choose to re-raise the event.
The specified flavor was invalid.
An attempt has been made to create a reference that is
circular (for example, deriving a class from itself).
The specified class is not supported.
An attempt was made to change a key when instances or derived
classes are already using the key.
An attempt was made to change an index when instances or derived
classes are already using the index.
An attempt was made to create more properties than the
current version of the class supports.
A property was redefined with a conflicting type in a
derived class.
An attempt was made in a derived class to override a
non-overrideable qualifier.
A method was redeclared with a conflicting signature in a
derived class.
An attempt was made to execute a method not marked with
[implemented] in any relevant class.
An attempt was made to execute a method marked with
[disabled].
The refresher is busy with another operation.
The filtering query is syntactically invalid.
The FROM clause of a filtering query references a class
that is not an event class.
A GROUP BY clause was used without the corresponding
GROUP WITHIN clause.
A GROUP BY clause was used. Aggregation on all properties
is not supported.
Dot notation was used on a property that is not an
embedded object.
A GROUP BY clause references a property that is an
embedded object without using dot notation.
An event provider registration query
() did not specify the classes for which
events were provided.
An request was made to back up or restore the repository
while WinMgmt.exe was using it.
The asynchronous delivery queue overflowed from the
event consumer being too slow.
The operation failed because the client did not have the
necessary security privilege.
The operator is not valid for this property type.
The user specified a username, password, or authority on a
local connection. The user must use an empty user name and password and rely on
default security.
The class was made abstract when its base class is not
abstract.
An amended object was used in a put operation without the
WBEM_FLAG_USE_AMENDED_QUALIFIERS flag being specified.
The client was not retrieving objects quickly enough from
an enumeration.
The provider registration overlaps with the system event
domain.
A WITHIN clause was not used in this query.
Represents management exceptions.
using System;
using System.Management;
// This sample demonstrates how to display error
// information stored in a ManagementException object.
class Sample_ManagementException
{
public static int Main(string[] args)
{
try
{
ManagementObject disk =
new ManagementObject("Win32_LogicalDisk.DeviceID='BAD:'");
disk.Get(); // throws ManagementException
Console.WriteLine("This shouldn't be displayed.");
}
catch (ManagementException e)
{
Console.WriteLine("ErrorCode " + e.ErrorCode);
Console.WriteLine("Message " + e.Message);
Console.WriteLine("Source " + e.Source);
if (e.ErrorInformation) //extended error object
Console.WriteLine("Extended Description : " + e.ErrorInformation["Description"]);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to display error
' information stored in a ManagementException object.
Class Sample_ManagementException
Overloads Public Shared Function Main(args() As String) As Integer
Try
Dim disk As New ManagementObject("Win32_LogicalDisk.DeviceID='BAD:'")
disk.Get() ' throws ManagementException
Console.WriteLine("This shouldn't be displayed.")
Catch e As ManagementException
Console.WriteLine("ErrorCode " & e.ErrorCode)
Console.WriteLine("Message " & e.Message)
Console.WriteLine("Source " & e.Source)
If e.ErrorInformation != Nothing Then 'extended error object
Console.WriteLine("Extended Description : " & e.ErrorInformation("Description"))
End If
End Try
Return 0
End Function
End Class
Initializes a new instance of the class that is serializable.
The to populate with data.
The destination (see ) for this serialization.
Initializes a new instance of the class
Initializes a new instance of the
class with a specified error message.
The message that describes the error.
Initializes a empty new instance of the class
The message that describes the error.
The exception that is the cause of the current exception. If the innerException
parameter is not a null reference (Nothing in Visual Basic), the current exception is raised in a catch
block that handles the inner exception.
Populates the object with the data needed to
serialize the
object.
The to populate with data.
The destination (see ) for this serialization.
Gets the extended error object provided by WMI.
A representing the
extended error object provided by WMI, if available;
otherwise.
Gets the error code reported by WMI, which caused this exception.
A value representing the error code returned by
the WMI operation.
Represents a collection of named values
suitable for use as context information to WMI operations. The
names are case-insensitive.
Initializes a new instance
of the class.
Initializes a new instance of the class, which is empty. This is
the default constructor.
Initializes a new instance of the class that is serializable
and uses the specified
and .
The to populate with data.
The destination (see ) for this serialization.
Internal method to return an IWbemContext representation
of the named value collection.
Adds a single-named value to the collection.
The name of the new value.
The value to be associated with the name.
Removes a single-named value from the collection.
If the collection does not contain an element with the
specified name, the collection remains unchanged and no
exception is thrown.
The name of the value to be removed.
Removes all entries from the collection.
Creates a clone of the collection. Individual values
are cloned. If a value does not support cloning, then a
is thrown.
The new copy of the collection.
Returns the value associated with the specified name from this collection.
The name of the value to be returned.
An containing the
value of the specified item in this collection.
Delegate definition for the IdentifierChanged event.
This event is used to signal the ManagementObject that an identifying property
has been changed. Identifying properties are the ones that identify the object,
namely the scope, path and options.
Delegate definition for InternalObjectPut event. This is used so that
the WmiEventSink can signal to this object that the async Put call has
completed.
Represents a data management object.
using System;
using System.Management;
// This example demonstrates reading a property of a ManagementObject.
class Sample_ManagementObject
{
public static int Main(string[] args) {
ManagementObject disk = new ManagementObject(
"win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
return 0;
}
}
Imports System
Imports System.Management
' This example demonstrates reading a property of a ManagementObject.
Class Sample_ManagementObject
Overloads Public Shared Function Main(args() As String) As Integer
Dim disk As New ManagementObject("win32_logicaldisk.deviceid=""c:""")
disk.Get()
Console.WriteLine(("Logical Disk Size = " & disk("Size").ToString() _
& " bytes"))
Return 0
End Function
End Class
Initializes a new instance of the class.
Initializes a new instance of the class. This is the
default constructor.
ManagementObject o = new ManagementObject();
//Now set the path on this object to bind it to a 'real' manageable entity
o.Path = new ManagementPath("Win32_LogicalDisk='c:'");
//Now it can be used
Console.WriteLine(o["FreeSpace"]);
Dim o As New ManagementObject()
Dim mp As New ManagementPath("Win32_LogicalDisk='c:'")
'Now set the path on this object to bind it to a 'real' manageable entity
o.Path = mp
'Now it can be used
Console.WriteLine(o("FreeSpace"))
Initializes a new instance of the class for the specified WMI
object path. The path is provided as a .
A that contains a path to a WMI object.
ManagementPath p = new ManagementPath("Win32_Service.Name='Alerter'");
ManagementObject o = new ManagementObject(p);
Dim p As New ManagementPath("Win32_Service.Name=""Alerter""")
Dim o As New ManagementObject(p)
Initializes a new instance of the class for the specified WMI object path. The path
is provided as a string.
A WMI path.
If the specified path is a relative path only (a server
or namespace is not specified), the default path is the local machine, and the
default namespace is the
path (by default, root\cimv2). If the user specifies a
full path, the default settings are overridden.
ManagementObject o = new ManagementObject("Win32_Service.Name='Alerter'");
//or with a full path :
ManagementObject o = new ManagementObject("\\\\MyServer\\root\\MyApp:MyClass.Key='abc'");
Dim o As New ManagementObject("Win32_Service.Name=""Alerter""")
//or with a full path :
Dim o As New ManagementObject("\\\\MyServer\\root\\MyApp:MyClass.Key=""abc""");
Initializes a new instance of the class bound to the specified
WMI path, including the specified additional options.
A containing the WMI path.
An containing additional options for binding to the WMI object. This parameter could be null if default options are to be used.
ManagementPath p = new ManagementPath("Win32_ComputerSystem.Name='MyMachine'");
//Set options for no context info, but requests amended qualifiers
//to be contained in the object
ObjectGetOptions opt = new ObjectGetOptions(null, true);
ManagementObject o = new ManagementObject(p, opt);
Console.WriteLine(o.GetQualifierValue("Description"));
Dim p As New ManagementPath("Win32_ComputerSystem.Name=""MyMachine""")
'Set options for no context info, but requests amended qualifiers
'to be contained in the object
Dim opt As New ObjectGetOptions(null, true)
Dim o As New ManagementObject(p, opt)
Console.WriteLine(o.GetQualifierValue("Description"));
Initializes a new instance of the class bound to the specified WMI path, including the
specified additional options. In this variant, the path can be specified as a
string.
The WMI path to the object.
An representing options to get the specified WMI object.
//Set options for no context info,
//but requests amended qualifiers to be contained in the object
ObjectGetOptions opt = new ObjectGetOptions(null, true);
ManagementObject o = new ManagementObject("Win32_ComputerSystem.Name='MyMachine'", opt);
Console.WriteLine(o.GetQualifierValue("Description"));
'Set options for no context info,
'but requests amended qualifiers to be contained in the object
Dim opt As New ObjectGetOptions(null, true)
Dim o As New ManagementObject("Win32_ComputerSystem.Name=""MyMachine""", opt);
Console.WriteLine(o.GetQualifierValue("Description"))
Initializes a new instance of the
class bound to the specified WMI path that includes the specified options.
A representing the scope in which the WMI object resides. In this version, scopes can only be WMI namespaces.
A representing the WMI path to the manageable object.
An specifying additional options for getting the object.
Because WMI paths can be relative or full, a conflict between the scope and the path
specified may arise. However, if a scope is specified and
a relative WMI path is specified, then there is no conflict. The
following are some possible conflicts:
If a scope is not specified and a relative WMI
path is specified, then the scope will default to the local machine's .
If a scope is not specified and a full WMI path is
specified, then the scope will be inferred from the scope portion of the full
path. For example, the full WMI path: \\MyMachine\root\MyNamespace:MyClass.Name='abc' will
represent the WMI object 'MyClass.Name='abc'" in the scope
'\\MyMachine\root\MyNamespace'.
If a scope is specified and a full WMI path is specified, then the scope
will override the scope portion of the full path. For example, if the following
scope was specified: \\MyMachine\root\MyScope, and the following full path was
specified: \\MyMachine\root\MyNamespace:MyClass.Name='abc', then look for the
following object:
\\MyMachine\root\MyScope:MyClass.Name=
'abc'
(the scope part of the full path is ignored).
ManagementScope s = new ManagementScope("\\\\MyMachine\\root\\cimv2");
ManagementPath p = new ManagementPath("Win32_LogicalDisk.Name='c:'");
ManagementObject o = new ManagementObject(s,p);
Dim s As New ManagementScope("\\MyMachine\root\cimv2");
Dim p As New ManagementPath("Win32_LogicalDisk.Name=""c:""");
Dim o As New ManagementObject(s,p);
Initializes a new instance of the class
bound to the specified WMI path, and includes the specified options. The scope and
the path are specified as strings.
The scope for the WMI object.
The WMI object path.
An representing additional options for getting the WMI object.
See the equivalent overload for details.
GetObjectOptions opt = new GetObjectOptions(null, true);
ManagementObject o = new ManagementObject("root\\MyNamespace", "MyClass.Name='abc'", opt);
Dim opt As New GetObjectOptions(null, true)
Dim o As New ManagementObject("root\MyNamespace", "MyClass.Name=""abc""", opt);
Initializes a new instance of the class that is serializable.
The to populate with data.
The destination (see ) for this serialization.
Gets or sets the scope in which this object resides.
A .
Changing
this property after the management object has been bound to a WMI object in
a particular namespace results in releasing the original WMI object. This causes the management object to
be rebound to the new object specified by the new path properties and scope
values.
The rebinding is performed in a "lazy" manner, that is, only when a requested
value requires the management object to be bound to the WMI object. Changes can
be made to more than just this property before attempting to rebind (for example, modifying the scope
and path properties simultaneously).
//Create the object with the default namespace (root\cimv2)
ManagementObject o = new ManagementObject();
//Change the scope (=namespace) of this object to the one specified.
o.Scope = new ManagementScope("root\\MyAppNamespace");
'Create the object with the default namespace (root\cimv2)
Dim o As New ManagementObject()
'Change the scope (=namespace) of this object to the one specified.
o.Scope = New ManagementScope("root\MyAppNamespace")
Gets or sets the object's WMI path.
A representing the object's path.
Changing the property after the management
object has been bound to a WMI object in a particular namespace results in releasing
the original WMI object. This causes the management object to be rebound to
the new object specified by the new path properties and scope values.
The rebinding is performed in a "lazy" manner, that is, only when a requested
value requires the management object to be bound to the WMI object. Changes can
be made to more than just the property before attempting to rebind (for example,
modifying the scope and path properties simultaneously).
ManagementObject o = new ManagementObject();
//Specify the WMI path to which this object should be bound to
o.Path = new ManagementPath("MyClass.Name='MyName'");
Dim o As New ManagementObject()
'Specify the WMI path to which this object should be bound to
o.Path = New ManagementPath("MyClass.Name=""MyName""");
Gets or
sets additional information to use when retrieving the object.
An to use when retrieving the object.
When the property is
changed after the management object has been bound to a WMI object, the management object
is disconnected from the original WMI object and later rebound using the new
options.
//Contains default options
ManagementObject o = new ManagementObject("MyClass.Name='abc'");
//Replace default options, in this case requesting retrieval of
//amended qualifiers along with the WMI object.
o.Options = new ObjectGetOptions(null, true);
'Contains default options
Dim o As New ManagementObject("MyClass.Name=""abc""")
'Replace default options, in this case requesting retrieval of
'amended qualifiers along with the WMI object.
o.Options = New ObjectGetOptions(null, true)
Gets or sets the path to the object's class.
A representing the path to the object's
class.
This property is read-only.
ManagementObject o = new ManagementObject("MyClass.Name='abc'");
//Get the class definition for the object above.
ManagementClass c = new ManagementClass(o.ClassPath);
Dim o As New ManagementObject("MyClass.Name=""abc""")
'Get the class definition for the object above.
Dim c As New ManagementClass(o.ClassPath);
Binds to the management object.
Binds to the management object.
The method is implicitly
invoked at the first attempt to get or set information to the WMI object. It
can also be explicitly invoked at the user's discretion, to better control the
timing and manner of retrieval.
ManagementObject o = new ManagementObject("MyClass.Name='abc'");
string s = o["SomeProperty"]; //this causes an implicit Get().
//or :
ManagementObject o= new ManagementObject("MyClass.Name= 'abc'");
o.Get(); //explicitly
//Now it's faster because the object has already been retrieved.
string s = o["SomeProperty"];
Dim o As New ManagementObject("MyClass.Name=""abc""")
string s = o("SomeProperty") 'this causes an implicit Get().
'or :
Dim o As New ManagementObject("MyClass.Name= ""abc""")
o.Get() 'explicitly
'Now it's faster because the object has already been retrieved.
string s = o("SomeProperty");
Binds to the management object asynchronously.
The object to receive the results of the operation as events.
The method will issue the request to get the object
and then will immediately return. The results of the operation will then be
delivered through events being fired on the watcher object provided.
ManagementObject o = new ManagementObject("MyClass.Name='abc'");
//Set up handlers for asynchronous get
MyHandler h = new MyHandler();
ManagementOperationObserver ob = new ManagementOperationObserver();
ob.Completed += new CompletedEventHandler(h.Done);
//Get the object asynchronously
o.Get(ob);
//Wait until operation is completed
while (!h.Completed)
System.Threading.Thread.Sleep (1000);
//Here we can use the object
Console.WriteLine(o["SomeProperty"]);
public class MyHandler
{
private bool completed = false;
public void Done(object sender, CompletedEventArgs e) {
Console.WriteLine("async Get completed !");
completed = true;
}
public bool Completed {
get {
return completed;
}
}
}
Dim o As New ManagementObject("MyClass.Name=""abc""")
'Set up handlers for asynchronous get
Dim h As New MyHandler()
Dim ob As New ManagementOperationObserver()
ob.Completed += New CompletedEventHandler(h.Done)
'Get the object asynchronously
o.Get(ob)
'Wait until operation is completed
While Not h.Completed
System.Threading.Thread.Sleep(1000)
End While
'Here we can use the object
Console.WriteLine(o("SomeProperty"))
Public Class MyHandler
Private _completed As Boolean = false;
Public Sub Done(sender As Object, e As EventArrivedEventArgs)
Console.WriteLine("async Get completed !")
_completed = True
End Sub
Public ReadOnly Property Completed() As Boolean
Get
Return _completed
End Get
End Property
End Class
Gets a collection of objects related to the object (associators).
Gets a collection of objects related to the object (associators).
A containing the
related objects.
The operation is equivalent to an ASSOCIATORS OF query where ResultClass = relatedClass.
ManagementObject o = new ManagementObject("Win32_Service='Alerter'");
foreach (ManagementBaseObject b in o.GetRelated())
Console.WriteLine("Object related to Alerter service : ", b.Path);
Dim o As New ManagementObject("Win32_Service=""Alerter""")
Dim b As ManagementBaseObject
For Each b In o.GetRelated()
Console.WriteLine("Object related to Alerter service : ", b.Path)
Next b
Gets a collection of objects related to the object (associators).
A class of related objects.
A containing the related objects.
ManagementObject o = new ManagementObject("Win32_Service='Alerter'");
foreach (ManagementBaseObject b in o.GetRelated("Win32_Service")
Console.WriteLine("Service related to the Alerter service {0} is {1}", b["Name"], b["State"]);
Dim o As New ManagementObject("Win32_Service=""Alerter""");
Dim b As ManagementBaseObject
For Each b in o.GetRelated("Win32_Service")
Console.WriteLine("Service related to the Alerter service {0} is {1}", b("Name"), b("State"))
Next b
Gets a collection of objects related to the object (associators).
The class of the related objects.
The relationship class of interest.
The qualifier required to be present on the relationship class.
The qualifier required to be present on the related class.
The role that the related class is playing in the relationship.
The role that this class is playing in the relationship.
When this method returns, it contains only class definitions for the instances that match the query.
Extended options for how to execute the query.
A containing the related objects.
This operation is equivalent to an ASSOCIATORS OF query where ResultClass = <relatedClass>.
Gets a collection of objects
related to the object (associators) asynchronously. This call returns immediately, and a
delegate is called when the results are available.
The object to use to return results.
Gets a collection of objects related to the object (associators).
The object to use to return results.
The class of related objects.
This operation is equivalent to an ASSOCIATORS OF query where ResultClass = <relatedClass>.
Gets a collection of objects related to the object (associators).
The object to use to return results.
The class of the related objects.
The relationship class of interest.
The qualifier required to be present on the relationship class.
The qualifier required to be present on the related class.
The role that the related class is playing in the relationship.
The role that this class is playing in the relationship.
Return only class definitions for the instances that match the query.
Extended options for how to execute the query.
This operation is equivalent to an ASSOCIATORS OF query where ResultClass = <relatedClass>.
Gets a collection of associations to the object.
Gets a collection of associations to the object.
A containing the association objects.
The operation is equivalent to a REFERENCES OF query.
Gets a collection of associations to the object.
The associations to include.
A containing the association objects.
This operation is equivalent to a REFERENCES OF query where the AssocClass = <relationshipClass>.
Gets a collection of associations to the object.
The type of relationship of interest.
The qualifier to be present on the relationship.
The role of this object in the relationship.
When this method returns, it contains only the class definitions for the result set.
The extended options for the query execution.
A containing the association objects.
This operation is equivalent to a REFERENCES OF query with possibly all the extensions.
Gets a collection of associations to the object.
The object to use to return results.
This operation is equivalent to a REFERENCES OF query
Gets a collection of associations to the object.
The object to use to return results.
The associations to include.
This operation is equivalent to a REFERENCES OF query where the AssocClass = <relationshipClass>.
Gets a collection of associations to the object.
The object to use to return results.
The type of relationship of interest.
The qualifier to be present on the relationship.
The role of this object in the relationship.
When this method returns, it contains only the class definitions for the result set.
The extended options for the query execution.
This operation is equivalent to a REFERENCES OF query with possibly all the extensions.
Commits the changes to the object.
Commits the changes to the object.
A containing the path to the committed
object.
Commits the changes to the object.
The options for how to commit the changes.
A containing the path to the committed object.
Commits the changes to the object, asynchronously.
A used to handle the progress and results of the asynchronous operation.
Commits the changes to the object asynchronously and
using the specified options.
A used to handle the progress and results of the asynchronous operation.
A used to specify additional options for the commit operation.
Copies the object to a different location.
Copies the object to a different location.
The to which the object should be copied.
The new path of the copied object.
Copies the object to a different location.
The path to which the object should be copied.
The new path of the copied object.
Copies the object to a different location.
The path to which the object should be copied.
The options for how the object should be put.
The new path of the copied object.
Copies the object to a different location.
The to which the object should be copied.
The options for how the object should be put.
The new path of the copied object.
Copies the object to a different location, asynchronously.
The object that will receive the results of the operation.
A specifying the path to which the object should be copied.
Copies the object to a different location, asynchronously.
The object that will receive the results of the operation.
The path to which the object should be copied.
Copies the object to a different location, asynchronously.
The object that will receive the results of the operation.
The path to which the object should be copied.
The options for how the object should be put.
Copies the object to a different location, asynchronously.
The object that will receive the results of the operation.
The path to which the object should be copied.
The options for how the object should be put.
Deletes the object.
Deletes the object.
Deletes the object.
The options for how to delete the object.
Deletes the object.
The object that will receive the results of the operation.
Deletes the object.
The object that will receive the results of the operation.
The options for how to delete the object.
Invokes a method on the object.
Invokes a method on the object.
The name of the method to execute.
An array containing parameter values.
The value returned by the method.
If the method is static, the execution
should still succeed.
using System;
using System.Management;
// This sample demonstrates invoking a WMI method using an array of arguments.
public class InvokeMethod
{
public static void Main()
{
//Get the object on which the method will be invoked
ManagementClass processClass = new ManagementClass("Win32_Process");
//Create an array containing all arguments for the method
object[] methodArgs = {"notepad.exe", null, null, 0};
//Execute the method
object result = processClass.InvokeMethod ("Create", methodArgs);
//Display results
Console.WriteLine ("Creation of process returned: " + result);
Console.WriteLine ("Process id: " + methodArgs[3]);
}
}
Imports System
Imports System.Management
' This sample demonstrates invoking a WMI method using an array of arguments.
Class InvokeMethod
Public Overloads Shared Function Main(ByVal args() As String) As Integer
' Get the object on which the method will be invoked
Dim processClass As New ManagementClass("Win32_Process")
' Create an array containing all arguments for the method
Dim methodArgs() As Object = {"notepad.exe", Nothing, Nothing, 0}
' Execute the method
Dim result As Object = processClass.InvokeMethod("Create", methodArgs)
'Display results
Console.WriteLine("Creation of process returned: {0}", result)
Console.WriteLine("Process id: {0}", methodArgs(3))
Return 0
End Function
End Class
Invokes a method on the object, asynchronously.
The object to receive the results of the operation.
The name of the method to execute.
An array containing parameter values.
If the method is static, the execution
should still succeed.
Invokes a method on the WMI object. The input and output
parameters are represented as
objects.
The name of the method to execute.
A holding the input parameters to the method.
An containing additional options for the execution of the method.
A containing the
output parameters and return value of the executed method.
using System;
using System.Management;
// This sample demonstrates invoking a WMI method using parameter objects
public class InvokeMethod
{
public static void Main()
{
//Get the object on which the method will be invoked
ManagementClass processClass = new ManagementClass("Win32_Process");
//Get an input parameters object for this method
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
//Fill in input parameter values
inParams["CommandLine"] = "calc.exe";
//Execute the method
ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null);
//Display results
//Note: The return code of the method is provided in the "returnValue" property of the outParams object
Console.WriteLine("Creation of calculator process returned: " + outParams["returnValue"]);
Console.WriteLine("Process ID: " + outParams["processId"]);
}
}
Imports System
Imports System.Management
' This sample demonstrates invoking a WMI method using parameter objects
Class InvokeMethod
Public Overloads Shared Function Main(ByVal args() As String) As Integer
' Get the object on which the method will be invoked
Dim processClass As New ManagementClass("Win32_Process")
' Get an input parameters object for this method
Dim inParams As ManagementBaseObject = processClass.GetMethodParameters("Create")
' Fill in input parameter values
inParams("CommandLine") = "calc.exe"
' Execute the method
Dim outParams As ManagementBaseObject = processClass.InvokeMethod("Create", inParams, Nothing)
' Display results
' Note: The return code of the method is provided in the "returnValue" property of the outParams object
Console.WriteLine("Creation of calculator process returned: {0}", outParams("returnValue"))
Console.WriteLine("Process ID: {0}", outParams("processId"))
Return 0
End Function
End Class
Invokes a method on the object, asynchronously.
A used to handle the asynchronous execution's progress and results.
The name of the method to be executed.
A containing the input parameters for the method.
An containing additional options used to execute the method.
The method invokes the specified method execution and then
returns. Progress and results are reported through events on the .
Returns a representing the list of input parameters for a method.
The name of the method.
A containing the
input parameters to the method.
Gets the object containing the input parameters to a
method, and then fills in the values and passes the object to the call.
Creates a copy of the object.
The copied object.
Returns the full path of the object. This is an override of the
default object implementation.
The full path of
the object.
Represents different collections of management objects
retrieved through WMI. The objects in this collection are of -derived types, including and
.
The collection can be the result of a WMI
query executed through a object, or an enumeration of
management objects of a specified type retrieved through a representing that type.
In addition, this can be a collection of management objects related in a specified
way to a specific management object - in this case the collection would
be retrieved through a method such as .
The collection can be walked using the and objects in it can be inspected or
manipulated for various management tasks.
using System;
using System.Management;
// This example demonstrates how to enumerate instances of a ManagementClass object.
class Sample_ManagementObjectCollection
{
public static int Main(string[] args) {
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection disks = diskClass.GetInstances();
foreach (ManagementObject disk in disks) {
Console.WriteLine("Disk = " + disk["deviceid"]);
}
return 0;
}
}
Imports System
Imports System.Management
' This example demonstrates how to enumerate instances of a ManagementClass object.
Class Sample_ManagementObjectCollection
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("Win32_LogicalDisk")
Dim disks As ManagementObjectCollection = diskClass.GetInstances()
Dim disk As ManagementObject
For Each disk In disks
Console.WriteLine("Disk = " & disk("deviceid").ToString())
Next disk
Return 0
End Function
End Class
Disposes of resources the object is holding. This is the destructor for the object.
Releases resources associated with this object. After this
method has been called, an attempt to use this object will
result in an ObjectDisposedException being thrown.
Represents the number of objects in the collection.
The number of objects in the collection.
This property is very expensive - it requires that
all members of the collection be enumerated.
Represents whether the object is synchronized.
, if the object is synchronized;
otherwise, .
Represents the object to be used for synchronization.
The object to be used for synchronization.
Copies the collection to an array.
Copies the collection to an array.
An array to copy to.
The index to start from.
Copies the items in the collection to a
array.
The target array.
The index to start from.
Returns the enumerator for the collection. If the collection was retrieved from an operation that
specified the EnumerationOptions.Rewindable = false only one iteration through this enumerator is allowed.
Note that this applies to using the Count property of the collection as well since an iteration over the collection
is required. Due to this, code using the Count property should never specify EnumerationOptions.Rewindable = false.
An that can be used to iterate through the
collection.
Returns an enumerator that can iterate through a collection.
An that can be used to iterate
through the collection.
Represents the enumerator on the collection.
using System;
using System.Management;
// This example demonstrates how to enumerate all logical disks
// using the ManagementObjectEnumerator object.
class Sample_ManagementObjectEnumerator
{
public static int Main(string[] args) {
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection disks = diskClass.GetInstances();
ManagementObjectCollection.ManagementObjectEnumerator disksEnumerator =
disks.GetEnumerator();
while(disksEnumerator.MoveNext()) {
ManagementObject disk = (ManagementObject)disksEnumerator.Current;
Console.WriteLine("Disk found: " + disk["deviceid"]);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to enumerate all logical disks
' using ManagementObjectEnumerator object.
Class Sample_ManagementObjectEnumerator
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("Win32_LogicalDisk")
Dim disks As ManagementObjectCollection = diskClass.GetInstances()
Dim disksEnumerator As _
ManagementObjectCollection.ManagementObjectEnumerator = _
disks.GetEnumerator()
While disksEnumerator.MoveNext()
Dim disk As ManagementObject = _
CType(disksEnumerator.Current, ManagementObject)
Console.WriteLine("Disk found: " & disk("deviceid"))
End While
Return 0
End Function
End Class
Disposes of resources the object is holding. This is the destructor for the object.
Releases resources associated with this object. After this
method has been called, an attempt to use this object will
result in an ObjectDisposedException being thrown.
Gets the current that this enumerator points
to.
The current object in the enumeration.
Returns the current object in the enumeration.
The current object in the enumeration.
Indicates whether the enumerator has moved to
the next object in the enumeration.
, if the enumerator was
successfully advanced to the next element; if the enumerator has
passed the end of the collection.
Resets the enumerator to the beginning of the collection.
Retrieves a collection of management objects based
on a specified query.
This class is one of the more commonly used entry points to retrieving
management information. For example, it can be used to enumerate all disk
drives, network adapters, processes and many more management objects on a
system, or to query for all network connections that are up, services that are
paused etc.
When instantiated, an instance of this class takes as input a WMI
query represented in an or it's derivatives, and optionally a representing the WMI namespace
to execute the query in. It can also take additional advanced
options in an object. When the Get() method on this object
is invoked, the ManagementObjectSearcher executes the given query in the
specified scope and returns a collection of management objects that match the
query in a .
using System;
using System.Management;
// This sample demonstrates perform a query using
// ManagementObjectSearcher object.
class Sample_ManagementObjectSearcher
{
public static int Main(string[] args) {
ManagementObjectSearcher searcher = new
ManagementObjectSearcher("select * from win32_share");
foreach (ManagementObject share in searcher.Get()) {
Console.WriteLine("Share = " + share["Name"]);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates perform a query using
' ManagementObjectSearcher object.
Class Sample_ManagementObjectSearcher
Overloads Public Shared Function Main(args() As String) As Integer
Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_Share")
Dim share As ManagementObject
For Each share In searcher.Get()
Console.WriteLine("Share = " & share("Name").ToString())
Next share
Return 0
End Function
End Class
Initializes a new instance of the class.
Initializes a new instance of the class. After some properties on
this object are set, the object can be used to invoke a query for management information. This is the default
constructor.
ManagementObjectSearcher s = new ManagementObjectSearcher();
Dim s As New ManagementObjectSearcher()
Initializes a new instance of the class used
to invoke the specified query for management information.
The WMI query to be invoked by the object.
ManagementObjectSearcher s =
new ManagementObjectSearcher("SELECT * FROM Win32_Service");
Dim s As New ManagementObjectSearcher("SELECT * FROM Win32_Service")
Initializes a new instance of the class used to invoke the
specified query for management information.
An representing the query to be invoked by the searcher.
SelectQuery q = new SelectQuery("Win32_Service", "State='Running'");
ManagementObjectSearcher s = new ManagementObjectSearcher(q);
Dim q As New SelectQuery("Win32_Service", "State=""Running""")
Dim s As New ManagementObjectSearcher(q)
Initializes a new instance of the class used to invoke the
specified query in the specified scope.
The scope in which to query.
The query to be invoked.
If no scope is specified, the default scope () is used.
ManagementObjectSearcher s = new ManagementObjectSearcher(
"root\\MyApp",
"SELECT * FROM MyClass WHERE MyProp=5");
Dim s As New ManagementObjectSearcher( _
"root\MyApp", _
"SELECT * FROM MyClass WHERE MyProp=5")
Initializes a new instance of the class used to invoke the
specified query in the specified scope.
A representing the scope in which to invoke the query.
An representing the query to be invoked.
If no scope is specified, the default scope () is
used.
ManagementScope myScope = new ManagementScope("root\\MyApp");
SelectQuery q = new SelectQuery("Win32_Environment", "User=<system>");
ManagementObjectSearcher s = new ManagementObjectSearcher(myScope,q);
Dim myScope As New ManagementScope("root\MyApp")
Dim q As New SelectQuery("Win32_Environment", "User=<system>")
Dim s As New ManagementObjectSearcher(myScope,q)
Initializes a new instance of the class used to invoke the specified
query, in the specified scope, and with the specified options.
The scope in which the query should be invoked.
The query to be invoked.
An specifying additional options for the query.
ManagementObjectSearcher s = new ManagementObjectSearcher(
"root\\MyApp",
"SELECT * FROM MyClass",
new EnumerationOptions(null, InfiniteTimeout, 1, true, false, true);
Dim s As New ManagementObjectSearcher( _
"root\MyApp", _
"SELECT * FROM MyClass", _
New EnumerationOptions(Null, InfiniteTimeout, 1, True, False, True)
Initializes a new instance of the class to be
used to invoke the specified query in the specified scope, with the specified
options.
A specifying the scope of the query
An specifying the query to be invoked
An specifying additional options to be used for the query.
ManagementScope scope = new ManagementScope("root\\MyApp");
SelectQuery q = new SelectQuery("SELECT * FROM MyClass");
EnumerationOptions o = new EnumerationOptions(null, InfiniteTimeout, 1, true, false, true);
ManagementObjectSearcher s = new ManagementObjectSearcher(scope, q, o);
Dim scope As New ManagementScope("root\MyApp")
Dim q As New SelectQuery("SELECT * FROM MyClass")
Dim o As New EnumerationOptions(Null, InfiniteTimeout, 1, True, False, True)
Dim s As New ManagementObjectSearcher(scope, q, o)
Gets or sets the scope in which to look for objects (the scope represents a WMI namespace).
The scope (namespace) in which to look for objects.
When the value of this property is changed,
the
is re-bound to the new scope.
ManagementObjectSearcher s = new ManagementObjectSearcher();
s.Scope = new ManagementScope("root\\MyApp");
Dim s As New ManagementObjectSearcher()
Dim ms As New ManagementScope ("root\MyApp")
s.Scope = ms
Gets or sets the query to be invoked in the
searcher (that is, the criteria to be applied to the search for management objects).
The criteria to apply to the query.
When the value of this property is changed, the
is reset to use the new query.
Gets or sets the options for how to search for objects.
The options for how to search for objects.
Invokes the specified WMI query and returns the resulting collection.
Invokes the specified WMI query and returns the
resulting collection.
A containing the objects that match the
specified query.
Invokes the WMI query, asynchronously, and binds to a watcher to deliver the results.
The watcher that raises events triggered by the operation.
Represents the method that will handle the event.
Represents the method that will handle the event.
Represents the method that will handle the event.
Represents the method that will handle the event.
Used to manage asynchronous operations and handle management information and events received asynchronously.
using System;
using System.Management;
// This sample demonstrates how to read a ManagementObject asychronously
// using the ManagementOperationObserver object.
class Sample_ManagementOperationObserver {
public static int Main(string[] args) {
//Set up a handler for the asynchronous callback
ManagementOperationObserver observer = new ManagementOperationObserver();
MyHandler completionHandler = new MyHandler();
observer.Completed += new CompletedEventHandler(completionHandler.Done);
//Invoke the asynchronous read of the object
ManagementObject disk = new ManagementObject("Win32_logicaldisk='C:'");
disk.Get(observer);
//For the purpose of this sample, we keep the main
// thread alive until the asynchronous operation is completed.
while (!completionHandler.IsComplete) {
System.Threading.Thread.Sleep(500);
}
Console.WriteLine("Size= " + disk["Size"] + " bytes.");
return 0;
}
public class MyHandler
{
private bool isComplete = false;
public void Done(object sender, CompletedEventArgs e) {
isComplete = true;
}
public bool IsComplete {
get {
return isComplete;
}
}
}
}
Imports System
Imports System.Management
' This sample demonstrates how to read a ManagementObject asychronously
' using the ManagementOperationObserver object.
Class Sample_ManagementOperationObserver
Overloads Public Shared Function Main(args() As String) As Integer
'Set up a handler for the asynchronous callback
Dim observer As New ManagementOperationObserver()
Dim completionHandler As New MyHandler()
AddHandler observer.Completed, AddressOf completionHandler.Done
' Invoke the object read asynchronously
Dim disk As New ManagementObject("Win32_logicaldisk='C:'")
disk.Get(observer)
' For the purpose of this sample, we keep the main
' thread alive until the asynchronous operation is finished.
While Not completionHandler.IsComplete Then
System.Threading.Thread.Sleep(500)
End While
Console.WriteLine("Size = " + disk("Size").ToString() & " bytes")
Return 0
End Function
Public Class MyHandler
Private _isComplete As Boolean = False
Public Sub Done(sender As Object, e As CompletedEventArgs)
_isComplete = True
End Sub 'Done
Public ReadOnly Property IsComplete() As Boolean
Get
Return _isComplete
End Get
End Property
End Class
End Class
Occurs when a new object is available.
Occurs when an operation has completed.
Occurs to indicate the progress of an ongoing operation.
Occurs when an object has been successfully committed.
Initializes a new instance of the class. This is the default constructor.
Cancels all outstanding operations.
Fires the ObjectReady event to whomsoever is listening
This class handles the posting of events to delegates. For each event
it queues a set of requests (one per target delegate) to the thread pool
to handle the event. It ensures that no single delegate can throw
an exception that prevents the event from reaching any other delegates.
It also ensures that the sender does not signal the processing of the
WMI event as "done" until all target delegates have signalled that they are
done.
Custom handler for firing a WMI event to a list of delegates. We use
the process thread pool to handle the firing.
The MulticastDelegate representing the collection
of targets for the event
The accompanying event arguments
Describes the authentication level to be used to connect to WMI. This is used for the COM connection to WMI.
The default COM authentication level. WMI uses the default Windows Authentication setting.
No COM authentication.
Connect-level COM authentication.
Call-level COM authentication.
Packet-level COM authentication.
Packet Integrity-level COM authentication.
Packet Privacy-level COM authentication.
The default COM authentication level. WMI uses the default Windows Authentication setting.
Describes the impersonation level to be used to connect to WMI.
Default impersonation.
Anonymous COM impersonation level that hides the
identity of the caller. Calls to WMI may fail
with this impersonation level.
Identify-level COM impersonation level that allows objects
to query the credentials of the caller. Calls to
WMI may fail with this impersonation level.
Impersonate-level COM impersonation level that allows
objects to use the credentials of the caller. This is the recommended impersonation level for WMI calls.
Delegate-level COM impersonation level that allows objects
to permit other objects to use the credentials of the caller. This
level, which will work with WMI calls but may constitute an unnecessary
security risk, is supported only under Windows 2000.
Describes the possible effects of saving an object to WMI when
using .
Invalid Type
Updates an existing object
only; does not create a new object.
Creates an object only;
does not update an existing object.
Saves the object, whether
updating an existing object or creating a new object.
Provides an abstract base class for all Options objects.
Options objects are used to customize different management operations.
Use one of the Options classes derived from this class, as
indicated by the signature of the operation being performed.
Specifies an infinite timeout.
Gets or sets a WMI context object. This is a
name-value pairs list to be passed through to a WMI provider that supports
context information for customized operation.
A name-value pairs list to be passed through to a WMI provider that
supports context information for customized operation.
Gets or sets the timeout to apply to the operation.
Note that for operations that return collections, this timeout applies to the
enumeration through the resulting collection, not the operation itself
(the
property is used for the latter).
This property is used to indicate that the operation should be performed semisynchronously.
The default value for this property is
, which means the operation will block.
The value specified must be positive.
Returns a copy of the object.
The cloned object.
Provides a base class for query and enumeration-related options
objects.
Use this class to customize enumeration of management
objects, traverse management object relationships, or query for
management objects.
using System;
using System.Management;
// This example demonstrates how to enumerate all top-level WMI classes
// and subclasses in root/cimv2 namespace.
class Sample_EnumerationOptions
{
public static int Main(string[] args) {
ManagementClass newClass = new ManagementClass();
EnumerationOptions options = new EnumerationOptions();
options.EnumerateDeep = false;
foreach (ManagementObject o in newClass.GetSubclasses(options)) {
Console.WriteLine(o["__Class"]);
}
return 0;
}
}
Imports System
Imports System.Management
' This example demonstrates how to enumerate all top-level WMI classes
' and subclasses in root/cimv2 namespace.
Class Sample_EnumerationOptions
Overloads Public Shared Function Main(args() As String) As Integer
Dim newClass As New ManagementClass()
Dim options As New EnumerationOptions()
options.EnumerateDeep = False
Dim o As ManagementObject
For Each o In newClass.GetSubclasses(options)
Console.WriteLine(o("__Class"))
Next o
Return 0
End Function
End Class
Gets or sets a value indicating whether the invoked operation should be
performed in a synchronous or semisynchronous fashion. If this property is set
to , the enumeration is invoked and the call returns immediately. The actual
retrieval of the results will occur when the resulting collection is walked.
if the invoked operation should
be performed in a synchronous or semisynchronous fashion; otherwise,
. The default value is .
Gets or sets the block size
for block operations. When enumerating through a collection, WMI will return results in
groups of the specified size.
The default value is 1.
Gets or sets a value indicating whether the collection is assumed to be
rewindable. If , the objects in the
collection will be kept available for multiple enumerations. If
, the collection
can only be enumerated one time.
if the collection is assumed to
be rewindable; otherwise, . The default value is
.
A rewindable collection is more costly in memory
consumption as all the objects need to be kept available at the same time.
In a collection defined as non-rewindable, the objects are discarded after being returned
in the enumeration.
Gets or sets a value indicating whether the objects returned from
WMI should contain amended information. Typically, amended information is localizable
information attached to the WMI object, such as object and property
descriptions.
if the objects returned from WMI
should contain amended information; otherwise, . The
default value is .
If descriptions and other amended information are not of
interest, setting this property to
is more
efficient.
Gets or sets a value indicating whether to the objects returned should have
locatable information in them. This ensures that the system properties, such as
, , and
, are non-NULL. This flag can only be used in queries,
and is ignored in enumerations.
if WMI
should ensure all returned objects have valid paths; otherwise,
. The default value is .
Gets or sets a value indicating whether the query should return a
prototype of the result set instead of the actual results. This flag is used for
prototyping.
if the
query should return a prototype of the result set instead of the actual results;
otherwise, . The default value is
.
Gets or sets a value indicating whether direct access to the WMI provider is requested for the specified class,
without any regard to its base class or derived classes.
if only
objects of the specified class should be received, without regard to derivation
or inheritance; otherwise, . The default value is
.
Gets or sets a value indicating whether recursive enumeration is requested
into all classes derived from the specified base class. If
, only immediate derived
class members are returned.
if recursive enumeration is requested
into all classes derived from the specified base class; otherwise,
. The default value is .
Initializes a new instance
of the class.
Initializes a new instance of the
class with default values (see the individual property descriptions
for what the default values are). This is the default constructor.
Initializes a new instance of the class to be used for queries or enumerations,
allowing the user to specify values for the different options.
The options context object containing provider-specific information that can be passed through to the provider.
The timeout value for enumerating through the results.
The number of items to retrieve at one time from WMI.
to specify whether the result set is rewindable (=allows multiple traversal or one-time); otherwise, .
to specify whether the operation should return immediately (semi-sync) or block until all results are available; otherwise, .
to specify whether the returned objects should contain amended (locale-aware) qualifiers; otherwise, .
to specify to WMI that it should ensure all returned objects have valid paths; otherwise, .
to return a prototype of the result set instead of the actual results; otherwise, .
to retrieve objects of only the specified class only or from derived classes as well; otherwise, .
to specify recursive enumeration in subclasses; otherwise, .
Returns a copy of the object.
The cloned object.
Specifies options for management event watching.
Use this class to customize subscriptions for watching management events.
using System;
using System.Management;
// This example demonstrates how to listen to an event using ManagementEventWatcher object.
class Sample_EventWatcherOptions
{
public static int Main(string[] args) {
ManagementClass newClass = new ManagementClass();
newClass["__CLASS"] = "TestDeletionClass";
newClass.Put();
EventWatcherOptions options = new EventWatcherOptions();
ManagementEventWatcher watcher = new ManagementEventWatcher(null,
new WqlEventQuery("__classdeletionevent"),
options);
MyHandler handler = new MyHandler();
watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
watcher.Start();
// Delete class to trigger event
newClass.Delete();
//For the purpose of this example, we will wait
// two seconds before main thread terminates.
System.Threading.Thread.Sleep(2000);
watcher.Stop();
return 0;
}
public class MyHandler
{
public void Arrived(object sender, EventArrivedEventArgs e) {
Console.WriteLine("Class Deleted= " +
((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]);
}
}
}
Imports System
Imports System.Management
' This example demonstrates how to listen to an event using the ManagementEventWatcher object.
Class Sample_EventWatcherOptions
Public Shared Sub Main()
Dim newClass As New ManagementClass()
newClass("__CLASS") = "TestDeletionClass"
newClass.Put()
Dim options As _
New EventWatcherOptions()
Dim watcher As New ManagementEventWatcher( _
Nothing, _
New WqlEventQuery("__classdeletionevent"), _
options)
Dim handler As New MyHandler()
AddHandler watcher.EventArrived, AddressOf handler.Arrived
watcher.Start()
' Delete class to trigger event
newClass.Delete()
' For the purpose of this example, we will wait
' two seconds before main thread terminates.
System.Threading.Thread.Sleep(2000)
watcher.Stop()
End Sub
Public Class MyHandler
Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
Console.WriteLine("Class Deleted = " & _
CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS"))
End Sub
End Class
End Class
Gets or sets the block size for block operations. When waiting for events, this
value specifies how many events to wait for before returning.
The default value is 1.
Initializes a new instance of the class.
Initializes a new instance of the class for event watching, using default values.
This is the default constructor.
Initializes a new instance of the class with the given
values.
The options context object containing provider-specific information to be passed through to the provider.
The timeout to wait for the next events.
The number of events to wait for in each block.
Returns a copy of the object.
The cloned object.
Specifies options for getting a management object.
Use this class to customize retrieval of a management object.
using System;
using System.Management;
// This example demonstrates how to set a timeout value and list
// all amended qualifiers in a ManagementClass object.
class Sample_ObjectGetOptions
{
public static int Main(string[] args) {
// Request amended qualifiers
ObjectGetOptions options =
new ObjectGetOptions(null, new TimeSpan(0,0,0,5), true);
ManagementClass diskClass =
new ManagementClass("root/cimv2", "Win32_Process", options);
foreach (QualifierData qualifier in diskClass.Qualifiers) {
Console.WriteLine(qualifier.Name + ":" + qualifier.Value);
}
return 0;
}
}
Imports System
Imports System.Management
' This example demonstrates how to set a timeout value and list
' all amended qualifiers in a ManagementClass object.
Class Sample_ObjectGetOptions
Overloads Public Shared Function Main(args() As String) As Integer
' Request amended qualifiers
Dim options As _
New ObjectGetOptions(Nothing, New TimeSpan(0, 0, 0, 5), True)
Dim diskClass As New ManagementClass( _
"root/cimv2", _
"Win32_Process", _
options)
Dim qualifier As QualifierData
For Each qualifier In diskClass.Qualifiers
Console.WriteLine(qualifier.Name & ":" & qualifier.Value)
Next qualifier
Return 0
End Function
End Class
Gets or sets a value indicating whether the objects returned from WMI should
contain amended information. Typically, amended information is localizable information
attached to the WMI object, such as object and property descriptions.
if the objects returned from WMI
should contain amended information; otherwise, . The
default value is .
Initializes a new instance of the class.
Initializes a new instance of the class for getting a WMI object, using
default values. This is the default constructor.
Initializes a new instance of the class for getting a WMI object, using the
specified provider-specific context.
A provider-specific, named-value pairs context object to be passed through to the provider.
Initializes a new instance of the class for getting a WMI object,
using the given options values.
A provider-specific, named-value pairs context object to be passed through to the provider.
The length of time to let the operation perform before it times out. The default is .
if the returned objects should contain amended (locale-aware) qualifiers; otherwise, .
Returns a copy of the object.
The cloned object.
Specifies options for committing management
object changes.
Use this class to customize how values are saved to a management object.
using System;
using System.Management;
// This example demonstrates how to specify a PutOptions using
// PutOptions object when saving a ManagementClass object to
// the WMI respository.
class Sample_PutOptions
{
public static int Main(string[] args) {
ManagementClass newClass = new ManagementClass("root/default",
String.Empty,
null);
newClass["__Class"] = "class999xc";
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOnly;
try
{
newClass.Put(options); //will fail if the class doesn't already exist
}
catch (ManagementException e)
{
Console.WriteLine("Couldn't update class: " + e.ErrorCode);
}
return 0;
}
}
Imports System
Imports System.Management
' This example demonstrates how to specify a PutOptions using
' PutOptions object when saving a ManagementClass object to
' WMI respository.
Class Sample_PutOptions
Overloads Public Shared Function Main(args() As String) As Integer
Dim newClass As New ManagementClass( _
"root/default", _
String.Empty, _
Nothing)
newClass("__Class") = "class999xc"
Dim options As New PutOptions()
options.Type = PutType.UpdateOnly 'will fail if the class doesn't already exist
Try
newClass.Put(options)
Catch e As ManagementException
Console.WriteLine("Couldn't update class: " & e.ErrorCode)
End Try
Return 0
End Function
End Class
Gets or sets a value indicating whether the objects returned from WMI should
contain amended information. Typically, amended information is localizable information
attached to the WMI object, such as object and property descriptions.
if the objects returned from WMI
should contain amended information; otherwise, . The
default value is .
Gets or sets the type of commit to be performed for the object.
The default value is .
Initializes a new instance of the class.
Initializes a new instance of the class for put operations, using default values.
This is the default constructor.
Initializes a new instance of the class for committing a WMI object, using the
specified provider-specific context.
A provider-specific, named-value pairs context object to be passed through to the provider.
Initializes a new instance of the class for committing a WMI object, using
the specified option values.
A provider-specific, named-value pairs object to be passed through to the provider.
The length of time to let the operation perform before it times out. The default is .
if the returned objects should contain amended (locale-aware) qualifiers; otherwise, .
The type of commit to be performed (update or create).
Returns a copy of the object.
The cloned object.
Specifies options for deleting a management
object.
using System;
using System.Management;
// This example demonstrates how to specify a timeout value
// when deleting a ManagementClass object.
class Sample_DeleteOptions
{
public static int Main(string[] args) {
ManagementClass newClass = new ManagementClass();
newClass["__CLASS"] = "ClassToDelete";
newClass.Put();
// Set deletion options: delete operation timeout value
DeleteOptions opt = new DeleteOptions(null, new TimeSpan(0,0,0,5));
ManagementClass dummyClassToDelete =
new ManagementClass("ClassToDelete");
dummyClassToDelete.Delete(opt);
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to specify a timeout value
' when deleting a ManagementClass object.
Class Sample_DeleteOptions
Overloads Public Shared Function Main(args() As String) As Integer
Dim newClass As New ManagementClass()
newClass("__CLASS") = "ClassToDelete"
newClass.Put()
' Set deletion options: delete operation timeout value
Dim opt As New DeleteOptions(Nothing, New TimeSpan(0, 0, 0, 5))
Dim dummyClassToDelete As New ManagementClass("ClassToDelete")
dummyClassToDelete.Delete(opt)
Return 0
End Function
End Class
Initializes a new instance of the class.
Initializes a new instance of the class for the delete operation, using default values.
This is the default constructor.
Initializes a new instance of the class for a delete operation, using
the specified values.
A provider-specific, named-value pairs object to be passed through to the provider.
The length of time to let the operation perform before it times out. The default value is . Setting this parameter will invoke the operation semisynchronously.
Returns a copy of the object.
A cloned object.
Specifies options for invoking a management method.
Use this class to customize the execution of a method on a management
object.
using System;
using System.Management;
// This example demonstrates how to stop a system service.
class Sample_InvokeMethodOptions
{
public static int Main(string[] args) {
ManagementObject service =
new ManagementObject("win32_service=\"winmgmt\"");
InvokeMethodOptions options = new InvokeMethodOptions();
options.Timeout = new TimeSpan(0,0,0,5);
ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options);
Console.WriteLine("Return Status = " + outParams["ReturnValue"]);
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to stop a system service.
Class Sample_InvokeMethodOptions
Overloads Public Shared Function Main(args() As String) As Integer
Dim service As New ManagementObject("win32_service=""winmgmt""")
Dim options As New InvokeMethodOptions()
options.Timeout = New TimeSpan(0, 0, 0, 5)
Dim outParams As ManagementBaseObject = service.InvokeMethod( _
"StopService", _
Nothing, _
options)
Console.WriteLine("Return Status = " & _
outParams("ReturnValue").ToString())
Return 0
End Function
End Class
Initializes a new instance of the class.
Initializes a new instance of the class for the operation, using default values.
This is the default constructor.
Initializes a new instance of the class for an invoke operation using
the specified values.
A provider-specific, named-value pairs object to be passed through to the provider.
The length of time to let the operation perform before it times out. The default value is . Setting this parameter will invoke the operation semisynchronously.
Returns a copy of the object.
The cloned object.
Specifies all settings required to make a WMI connection.
Use this class to customize a connection to WMI made via a
ManagementScope object.
using System;
using System.Management;
// This example demonstrates how to connect to remote machine
// using supplied credentials.
class Sample_ConnectionOptions
{
public static int Main(string[] args) {
ConnectionOptions options = new ConnectionOptions();
options.Username = "domain\\username";
options.Password = "password";
ManagementScope scope = new ManagementScope(
"\\\\servername\\root\\cimv2",
options);
try {
scope.Connect();
ManagementObject disk = new ManagementObject(
scope,
new ManagementPath("Win32_logicaldisk='c:'"),
null);
disk.Get();
}
catch (Exception e) {
Console.WriteLine("Failed to connect: " + e.Message);
}
return 0;
}
}
Imports System
Imports System.Management
' This example demonstrates how to connect to remote machine
' using supplied credentials.
Class Sample_ConnectionOptions
Overloads Public Shared Function Main(args() As String) As Integer
Dim options As New ConnectionOptions()
options.Username = "domain\username"
options.Password = "password"
Dim scope As New ManagementScope("\\servername\root\cimv2", options)
Try
scope.Connect()
Dim disk As New ManagementObject(scope, _
New ManagementPath("Win32_logicaldisk='c:'"), Nothing)
disk.Get()
Catch e As UnauthorizedAccessException
Console.WriteLine(("Failed to connect: " + e.Message))
End Try
Return 0
End Function
End Class
Gets or sets the locale to be used for the connection operation.
The default value is DEFAULTLOCALE.
Gets or sets the user name to be used for the connection operation.
Null if the connection will use the currently logged-on user; otherwise, a string representing the user name. The default value is null.
If the user name is from a domain other than the current
domain, the string may contain the domain name and user name, separated by a backslash:
string username = "EnterDomainHere\\EnterUsernameHere";
Sets the password for the specified user. The value can be set, but not retrieved.
The default value is null. If the user name is also
null, the credentials used will be those of the currently logged-on user.
A blank string ("") specifies a valid
zero-length password.
Sets the secure password for the specified user. The value can be set, but not retrieved.
The default value is null. If the user name is also
null, the credentials used will be those of the currently logged-on user.
A blank securestring ("") specifies a valid
zero-length password.
Gets or sets the authority to be used to authenticate the specified user.
If not null, this property can contain the name of the
Windows NT/Windows 2000 domain in which to obtain the user to
authenticate.
The property must be passed
as follows: If it begins with the string "Kerberos:", Kerberos
authentication will be used and this property should contain a Kerberos principal name. For
example, Kerberos:<principal name>.
If the property value begins with the string "NTLMDOMAIN:", NTLM
authentication will be used and the property should contain a NTLM domain name.
For example, NTLMDOMAIN:<domain name>.
If the property is null, NTLM authentication will be used and the NTLM domain
of the current user will be used.
Gets or sets the COM impersonation level to be used for operations in this connection.
The COM impersonation level to be used for operations in
this connection. The default value is , which indicates that the WMI provider can
impersonate the client when performing the requested operations in this connection.
The setting is advantageous when the provider is
a trusted application or service. It eliminates the need for the provider to
perform client identity and access checks for the requested operations. However,
note that if for some reason the provider cannot be trusted, allowing it to
impersonate the client may constitute a security threat. In such cases, it is
recommended that this property be set by the client to a lower value, such as
. Note that this may cause failure of the
provider to perform the requested operations, for lack of sufficient permissions
or inability to perform access checks.
Gets or sets the COM authentication level to be used for operations in this connection.
The COM authentication level to be used for operations
in this connection. The default value is , which indicates that the
client will use the authentication level requested by the server, according to
the standard DCOM negotiation process.
On Windows 2000 and below, the WMI service will request
Connect level authentication, while on Windows XP and higher it will request
Packet level authentication. If the client requires a specific authentication
setting, this property can be used to control the authentication level on this
particular connection. For example, the property can be set to
if the
client requires all communication to be encrypted.
Gets or sets a value indicating whether user privileges need to be enabled for
the connection operation. This property should only be used when the operation
performed requires a certain user privilege to be enabled
(for example, a machine reboot).
if user privileges need to be
enabled for the connection operation; otherwise, . The
default value is .
Initializes a new instance of the class.
Initializes a new instance of the class for the connection operation, using default values. This is the
default constructor.
Initializes a new instance of the class to be used for a WMI
connection, using the specified values.
The locale to be used for the connection.
The user name to be used for the connection. If null, the credentials of the currently logged-on user are used.
The password for the given user name. If the user name is also null, the credentials used will be those of the currently logged-on user.
The authority to be used to authenticate the specified user.
The COM impersonation level to be used for the connection.
The COM authentication level to be used for the connection.
to enable special user privileges; otherwise, . This parameter should only be used when performing an operation that requires special Windows NT user privileges.
A provider-specific, named value pairs object to be passed through to the provider.
Reserved for future use.
Initializes a new instance of the class to be used for a WMI
connection, using the specified values.
The locale to be used for the connection.
The user name to be used for the connection. If null, the credentials of the currently logged-on user are used.
The secure password for the given user name. If the user name is also null, the credentials used will be those of the currently logged-on user.
The authority to be used to authenticate the specified user.
The COM impersonation level to be used for the connection.
The COM authentication level to be used for the connection.
to enable special user privileges; otherwise, . This parameter should only be used when performing an operation that requires special Windows NT user privileges.
A provider-specific, named value pairs object to be passed through to the provider.
Reserved for future use.
Returns a copy of the object.
The cloned object.
Provides a wrapper for parsing and building paths to WMI objects.
using System;
using System.Management;
// This sample displays all properties in a ManagementPath object.
class Sample_ManagementPath
{
public static int Main(string[] args) {
ManagementPath path = new ManagementPath( "\\\\MyServer\\MyNamespace:Win32_logicaldisk='c:'");
// Results of full path parsing
Console.WriteLine("Path: " + path.Path);
Console.WriteLine("RelativePath: " + path.RelativePath);
Console.WriteLine("Server: " + path.Server);
Console.WriteLine("NamespacePath: " + path.NamespacePath);
Console.WriteLine("ClassName: " + path.ClassName);
Console.WriteLine("IsClass: " + path.IsClass);
Console.WriteLine("IsInstance: " + path.IsInstance);
Console.WriteLine("IsSingleton: " + path.IsSingleton);
// Change a portion of the full path
path.Server = "AnotherServer";
Console.WriteLine("New Path: " + path.Path);
return 0;
}
}
Imports System
Imports System.Management
'This sample displays all properties in a ManagementPath object.
Class Sample_ManagementPath Overloads
Public Shared Function Main(args() As String) As Integer
Dim path As _ New
ManagementPath("\\MyServer\MyNamespace:Win32_LogicalDisk='c:'")
' Results of full path parsing
Console.WriteLine("Path: " & path.Path)
Console.WriteLine("RelativePath: " & path.RelativePath)
Console.WriteLine("Server: " & path.Server)
Console.WriteLine("NamespacePath: " & path.NamespacePath)
Console.WriteLine("ClassName: " & path.ClassName)
Console.WriteLine("IsClass: " & path.IsClass)
Console.WriteLine("IsInstance: " & path.IsInstance)
Console.WriteLine("IsSingleton: " & path.IsSingleton)
' Change a portion of the full path
path.Server= "AnotherServer"
Console.WriteLine("New Path: " & path.Path)
Return 0
End Function
End Class
Internal static "factory" method for making a new ManagementPath
from the system property of a WMI object
The WMI object whose __PATH property will
be used to supply the returned object
Initializes a new instance
of the class.
Initializes a new instance of the class that is empty. This is the default constructor.
Initializes a new instance of the class for the given path.
The object path.
Returns the full object path as the string representation.
A string containing the full object
path represented by this object. This value is equivalent to the value of the
property.
Returns a copy of the .
The cloned object.
Standard Clone returns a copy of this ManagementPath as a generic "Object" type
The cloned object.
Gets or sets the default scope path used when no scope is specified.
The default scope is /-/ \\.\root\cimv2, and can be changed by setting this property.
By default the scope value is /-/ \\.\root\cimv2, or a different scope path if
the default was changed.
Sets the path as a new class path. This means that the path must have
a class name but not key values.
Sets the path as a new singleton object path. This means that it is a path to an instance but
there are no key values.
Gets or sets the string representation of the full path in the object.
A string containing the full path
represented in this object.
Gets or sets the relative path: class name and keys only.
A string containing the relative
path (not including the server and namespace portions) represented in this
object.
Gets or sets the server part of the path.
A string containing the server name
from the path represented in this object.
Gets or sets the namespace part of the path. Note that this does not include
the server name, which can be retrieved separately.
A string containing the namespace
portion of the path represented in this object.
Gets or sets the class portion of the path.
A string containing the name of the
class.
Gets or sets a value indicating whether this is a class path.
if this is a class path; otherwise,
.
Gets or sets a value indicating whether this is an instance path.
if this is an instance path; otherwise,
.
Gets or sets a value indicating whether this is a singleton instance path.
if this is a singleton instance path; otherwise,
.
Converts a String to a ManagementPath
Determines if this converter can convert an object in the given source type to the native type of the converter.
An ITypeDescriptorContext that provides a format context.
A Type that represents the type you wish to convert from.
true if this converter can perform the conversion; otherwise, false.
Gets a value indicating whether this converter can convert an object to the given destination type using the context.
An ITypeDescriptorContext that provides a format context.
A Type that represents the type you wish to convert to.
true if this converter can perform the conversion; otherwise, false.
Converts the given object to another type. The most common types to convert
are to and from a string object. The default implementation will make a call
to ToString on the object if the object is valid and if the destination
type is string. If this cannot convert to the desitnation type, this will
throw a NotSupportedException.
An ITypeDescriptorContext that provides a format context.
A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.
The Object to convert.
The Type to convert the value parameter to.
An Object that represents the converted value.
Provides an abstract base class for all management query objects.
This class is abstract; only
derivatives of it are actually used in the API.
Parses the query string and sets the property values accordingly.
The query string to be parsed.
Gets or sets the query in text format.
If the query object is
constructed with no parameters, the property is null until specifically set. If the
object was constructed with a specified query, the property returns the specified
query string.
Gets or sets the query language used in the query
string, defining the format of the query string.
Can be set to any supported query
language. "WQL" is the only value supported intrinsically by WMI.
Returns a copy of the object.
The cloned object.
Represents a management query that returns instances or classes.
This class or its derivatives are used to specify a
query in the . Use
a more specific query class whenever possible.
using System;
using System.Management;
// This sample demonstrates creating a query.
class Sample_ObjectQuery
{
public static int Main(string[] args)
{
ObjectQuery objectQuery = new ObjectQuery("select * from Win32_Share");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(objectQuery);
foreach (ManagementObject share in searcher.Get())
{
Console.WriteLine("Share = " + share["Name"]);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates creating a query.
Class Sample_ObjectQuery
Overloads Public Shared Function Main(args() As String) As Integer
Dim objectQuery As New ObjectQuery("select * from Win32_Share")
Dim searcher As New ManagementObjectSearcher(objectQuery)
Dim share As ManagementObject
For Each share In searcher.Get()
Console.WriteLine("Share = " & share("Name"))
Next share
Return 0
End Function
End Class
Initializes a new instance of the
class.
Initializes a new instance of the
class with no initialized values. This
is the default constructor.
Initializes a new instance of the
class
for a specific query string.
The string representation of the query.
Initializes a new instance of the
class for a specific
query string and language.
The query language in which this query is specified.
The string representation of the query.
Returns a copy of the object.
The cloned object.
Represents a WMI event query.
Objects of this class or its derivatives are used in
to subscribe to
WMI events. Use more specific derivatives of this class whenever possible.
using System;
using System.Management;
// This sample demonstrates how to subscribe to an event
// using the EventQuery object.
class Sample_EventQuery
{
public static int Main(string[] args)
{
//For this example, we make sure we have an arbitrary class on root\default
ManagementClass newClass = new ManagementClass(
"root\\default",
String.Empty,
null);
newClass["__Class"] = "TestWql";
newClass.Put();
//Create a query object for watching for class deletion events
EventQuery eventQuery = new EventQuery("select * from __classdeletionevent");
//Initialize an event watcher object with this query
ManagementEventWatcher watcher = new ManagementEventWatcher(
new ManagementScope("root/default"),
eventQuery);
//Set up a handler for incoming events
MyHandler handler = new MyHandler();
watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
//Start watching for events
watcher.Start();
//For this example, we delete the class to trigger an event
newClass.Delete();
//Nothing better to do - we loop to wait for an event to arrive.
while (!handler.IsArrived) {
System.Threading.Thread.Sleep(1000);
}
//In this example we only want to wait for one event, so we can stop watching
watcher.Stop();
//Get some values from the event.
//Note: this can also be done in the event handler.
ManagementBaseObject eventArg =
(ManagementBaseObject)(handler.ReturnedArgs.NewEvent["TargetClass"]);
Console.WriteLine("Class Deleted = " + eventArg["__CLASS"]);
return 0;
}
public class MyHandler
{
private bool isArrived = false;
private EventArrivedEventArgs args;
//Handles the event when it arrives
public void Arrived(object sender, EventArrivedEventArgs e) {
args = e;
isArrived = true;
}
//Public property to get at the event information stored in the handler
public EventArrivedEventArgs ReturnedArgs {
get {
return args;
}
}
//Used to determine whether the event has arrived or not.
public bool IsArrived {
get {
return isArrived;
}
}
}
}
Imports System
Imports System.Management
' This sample demonstrates how to subscribe an event
' using the EventQuery object.
Class Sample_EventQuery
Public Shared Sub Main()
'For this example, we make sure we have an arbitrary class on root\default
Dim newClass As New ManagementClass( _
"root\default", _
String.Empty, Nothing)
newClass("__Class") = "TestWql"
newClass.Put()
'Create a query object for watching for class deletion events
Dim eventQuery As New EventQuery("select * from __classdeletionevent")
'Initialize an event watcher object with this query
Dim watcher As New ManagementEventWatcher( _
New ManagementScope("root/default"), _
eventQuery)
'Set up a handler for incoming events
Dim handler As New MyHandler()
AddHandler watcher.EventArrived, AddressOf handler.Arrived
'Start watching for events
watcher.Start()
'For this example, we delete the class to trigger an event
newClass.Delete()
'Nothing better to do - we loop to wait for an event to arrive.
While Not handler.IsArrived
Console.Write("0")
System.Threading.Thread.Sleep(1000)
End While
'In this example we only want to wait for one event, so we can stop watching
watcher.Stop()
'Get some values from the event
'Note: this can also be done in the event handler.
Dim eventArg As ManagementBaseObject = CType( _
handler.ReturnedArgs.NewEvent("TargetClass"), _
ManagementBaseObject)
Console.WriteLine(("Class Deleted = " + eventArg("__CLASS")))
End Sub
Public Class MyHandler
Private _isArrived As Boolean = False
Private args As EventArrivedEventArgs
'Handles the event when it arrives
Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
args = e
_isArrived = True
End Sub
'Public property to get at the event information stored in the handler
Public ReadOnly Property ReturnedArgs() As EventArrivedEventArgs
Get
Return args
End Get
End Property
'Used to determine whether the event has arrived or not.
Public ReadOnly Property IsArrived() As Boolean
Get
Return _isArrived
End Get
End Property
End Class
End Class
Initializes a new instance of the
class.
Initializes a new instance of the
class. This is the
default constructor.
Initializes a new instance of the
class for the specified query.
A textual representation of the event query.
Initializes a new instance of the
class for the specified
language and query.
The language in which the query string is specified.
The string representation of the query.
Returns a copy of the object.
The cloned object.
Represents a WMI data query in WQL format.
using System;
using System.Management;
// This sample demonstrates how to use a WqlObjectQuery class to
// perform an object query.
class Sample_WqlObjectQuery
{
public static int Main(string[] args) {
WqlObjectQuery objectQuery = new WqlObjectQuery("select * from Win32_Share");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(objectQuery);
foreach (ManagementObject share in searcher.Get()) {
Console.WriteLine("Share = " + share["Name"]);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrate how to use a WqlObjectQuery class to
' perform an object query.
Class Sample_WqlObjectQuery
Overloads Public Shared Function Main(args() As String) As Integer
Dim objectQuery As New WqlObjectQuery("select * from Win32_Share")
Dim searcher As New ManagementObjectSearcher(objectQuery)
Dim share As ManagementObject
For Each share In searcher.Get()
Console.WriteLine("Share = " & share("Name"))
Next share
Return 0
End Function
End Class
Initializes a new instance of the class.
Initializes a new instance of the class. This is the
default constructor.
Initializes a new instance of the class initialized to the
specified query.
The representation of the data query.
Gets or sets the language of the query.
The value of this
property is always "WQL".
Creates a copy of the object.
The copied object.
Represents a WQL SELECT data query.
using System;
using System.Management;
// This sample demonstrates how to perform a WQL select query.
class Sample_SelectQuery
{
public static int Main(string[] args) {
SelectQuery selectQuery = new SelectQuery("win32_logicaldisk");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(selectQuery);
foreach (ManagementObject disk in searcher.Get()) {
Console.WriteLine(disk.ToString());
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to perform a WQL select query.
Class Sample_SelectQuery
Overloads Public Shared Function Main(args() As String) As Integer
Dim selectQuery As New SelectQuery("win32_logicaldisk")
Dim searcher As New ManagementObjectSearcher(selectQuery)
Dim disk As ManagementObject
For Each disk In searcher.Get()
Console.WriteLine(disk.ToString())
Next disk
Return 0
End Function
End Class
Initializes a new instance of the
class.
Initializes a new instance of the
class. This is the
default constructor.
Initializes a new instance of the class for the specified
query or the specified class name.
The entire query or the class name to use in the query. The parser in this class attempts to parse the string as a valid WQL SELECT query. If the parser is unsuccessful, it assumes the string is a class name.
SelectQuery s = new SelectQuery("SELECT * FROM Win32_Service WHERE State='Stopped');
or
//This is equivalent to "SELECT * FROM Win32_Service"
SelectQuery s = new SelectQuery("Win32_Service");
Dim s As New SelectQuery("SELECT * FROM Win32_Service WHERE State='Stopped')
or
//This is equivalent to "SELECT * FROM Win32_Service"
Dim s As New SelectQuery("Win32_Service")
Initializes a new instance of the
class with the specified
class name and condition.
The name of the class to select in the query.
The condition to be applied in the query.
SelectQuery s = new SelectQuery("Win32_Process", "HandleID=1234");
Dim s As New SelectQuery("Win32_Process", "HandleID=1234")
Initializes a new instance of the
class with the specified
class name and condition, selecting only the specified properties.
The name of the class from which to select.
The condition to be applied to instances of the selected class.
An array of property names to be returned in the query results.
String[] properties = {"VariableName", "VariableValue"};
SelectQuery s = new SelectQuery("Win32_Environment",
"User='<system>'",
properties);
Dim properties As String[] = {"VariableName", "VariableValue"}
Dim s As New SelectQuery("Win32_Environment", _
"User=""<system>""", _
properties)
Initializes a new instance of the
class for a schema query, optionally specifying a condition. For schema queries,
only the parameter is valid.
to indicate that this is a schema query; otherwise, . A value is invalid in this constructor.
The condition to be applied to form the result set of classes.
SelectQuery s = new SelectQuery(true, "__CLASS = 'Win32_Service'");
Dim s As New SelectQuery(true, "__CLASS = ""Win32_Service""")
Gets or sets the query in the , in string form.
A string representing the query.
Setting this
property value overrides any previous value stored in the object. In addition, setting this
property causes the other members of the object to be updated when the string
is reparsed.
SelectQuery s = new SelectQuery();
s.QueryString = "SELECT * FROM Win32_LogicalDisk";
Dim s As New SelectQuery()
s.QueryString = "SELECT * FROM Win32_LogicalDisk"
Gets or sets a value indicating whether this query is a schema query or an instances query.
if this query
should be evaluated over the schema; if the query should
be evaluated over instances.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new query type.
Gets or sets the class name to be selected from in the query.
A string representing the name of the
class.
Setting this property value
overrides any previous value stored in the object. The query string is
rebuilt to reflect the new class name.
SelectQuery s = new SelectQuery("SELECT * FROM Win32_LogicalDisk");
Console.WriteLine(s.QueryString); //output is : SELECT * FROM Win32_LogicalDisk
s.ClassName = "Win32_Process";
Console.WriteLine(s.QueryString); //output is : SELECT * FROM Win32_Process
Dim s As New SelectQuery("SELECT * FROM Win32_LogicalDisk")
Console.WriteLine(s.QueryString) 'output is : SELECT * FROM Win32_LogicalDisk
s.ClassName = "Win32_Process"
Console.WriteLine(s.QueryString) 'output is : SELECT * FROM Win32_Process
Gets or sets the condition to be applied in the SELECT
query.
A string containing the condition to
be applied in the SELECT query.
Setting this property value overrides any previous value
stored in the object. The query string is rebuilt to reflect the new
condition.
Gets or sets an array of property names to be
selected in the query.
A containing the names of the
properties to be selected in the query.
Setting this property value overrides any previous value stored
in the object. The query string is rebuilt to reflect the new
properties.
Builds the query string according to the current property values.
Parses the query string and sets the property values accordingly.
The query string to be parsed.
Creates a copy of the object.
The copied object.
Represents a WQL ASSOCIATORS OF data query.
It can be used for both instances and schema queries.
using System;
using System.Management;
// This sample demonstrates how to query all instances associated
// with Win32_LogicalDisk='C:'.
class Sample_RelatedObjectQuery
{
public static int Main(string[] args) {
//This query requests all objects related to the 'C:' drive.
RelatedObjectQuery relatedQuery =
new RelatedObjectQuery("win32_logicaldisk='c:'");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(relatedQuery);
foreach (ManagementObject relatedObject in searcher.Get()) {
Console.WriteLine(relatedObject.ToString());
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to query all instances associated
' with Win32_LogicalDisk='C:'.
Class Sample_RelatedObjectQuery
Overloads Public Shared Function Main(args() As String) As Integer
'This query requests all objects related to the 'C:' drive.
Dim relatedQuery As New RelatedObjectQuery("win32_logicaldisk='c:'")
Dim searcher As New ManagementObjectSearcher(relatedQuery)
Dim relatedObject As ManagementObject
For Each relatedObject In searcher.Get()
Console.WriteLine(relatedObject.ToString())
Next relatedObject
Return 0
End Function
End Class
Initializes a new instance
of the class.
Initializes a new instance of the class. This is the
default constructor.
Initializes a new instance of the class. If the specified string can be succesfully parsed as
a WQL query, it is considered to be the query string; otherwise, it is assumed to be the path of the source
object for the query. In this case, the query is assumed to be an instance query.
The query string or the path of the source object.
//This query retrieves all objects related to the 'mymachine' computer system
//It specifies the full query string in the constructor
RelatedObjectQuery q =
new RelatedObjectQuery("associators of {Win32_ComputerSystem.Name='mymachine'}");
//or
//This query retrieves all objects related to the 'Alerter' service
//It specifies only the object of interest in the constructor
RelatedObjectQuery q =
new RelatedObjectQuery("Win32_Service.Name='Alerter'");
'This query retrieves all objects related to the 'mymachine' computer system
'It specifies the full query string in the constructor
Dim q As New RelatedObjectQuery("associators of {Win32_ComputerSystem.Name='mymachine'}")
'or
'This query retrieves all objects related to the 'Alerter' service
'It specifies only the object of interest in the constructor
Dim q As New RelatedObjectQuery("Win32_Service.Name='Alerter'")
Initializes a new instance of the class for the given source object and related class.
The query is assumed to be an instance query (as opposed to a schema query).
The path of the source object for this query.
The related objects class.
Initializes a new instance of the class for the given set of parameters.
The query is assumed to be an instance query (as opposed to a schema query).
The path of the source object.
The related objects required class.
The relationship type.
The qualifier required to be present on the related objects.
The qualifier required to be present on the relationships.
The role that the related objects are required to play in the relationship.
The role that the source object is required to play in the relationship.
to return only the class definitions of the related objects; otherwise, .
Initializes a new instance of the class for a schema query using the given set
of parameters. This constructor is used for schema queries only: the first
parameter must be set to
.
to indicate that this is a schema query; otherwise, .
The path of the source class.
The related objects' required base class.
The relationship type.
The qualifier required to be present on the related objects.
The qualifier required to be present on the relationships.
The role that the related objects are required to play in the relationship.
The role that the source class is required to play in the relationship.
Gets or sets a value indicating whether this is a schema query or an instance query.
if this query
should be evaluated over the schema; if the query should
be evaluated over instances.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new query type.
Gets or sets the source object to be used for the query. For instance
queries, this is typically an instance path. For schema queries, this is typically a class name.
A string representing the path of the
object to be used for the query.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new source object.
Gets or sets the class of the endpoint objects.
A string containing the related class
name.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new related class.
To find all the Win32 services available on a computer, this property is set
to "Win32_Service" :
RelatedObjectQuery q = new RelatedObjectQuery("Win32_ComputerSystem='MySystem'");
q.RelatedClass = "Win32_Service";
Dim q As New RelatedObjectQuery("Win32_ComputerSystem=""MySystem""")
q.RelatedClass = "Win32_Service"
Gets or sets the type of relationship (association).
A string containing the relationship
class name.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new relationship class.
For example, for finding all the Win32 services dependent on
a service, this property should be set to the "Win32_DependentService" association class:
RelatedObjectQuery q = new RelatedObjectQuery("Win32_Service='TCP/IP'");
q.RelationshipClass = "Win32_DependentService";
Dim q As New RelatedObjectQuery("Win32_Service=""TCP/IP""")
q.RelationshipClass = "Win32_DependentService"
Gets or sets a qualifier required to be defined on the related objects.
A string containing the name of the
qualifier required on the related objects.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new qualifier.
Gets or sets a qualifier required to be defined on the relationship objects.
A string containing the name of the qualifier required
on the relationship objects.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new qualifier.
Gets or sets the role that the related objects returned should be playing in the relationship.
A string containing the role of the
related objects.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new role.
Gets or sets the role that the source object should be playing in the relationship.
A string containing the role of this object.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new role.
Gets or sets a value indicating that for all instances that adhere to the query, only their class definitions be returned.
This parameter is only valid for instance queries.
if the query
requests only class definitions of the result set; otherwise,
.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new flag.
Builds the query string according to the current property values.
Parses the query string and sets the property values accordingly.
The query string to be parsed.
Creates a copy of the object.
The copied object.
Represents a WQL REFERENCES OF data query.
The following example searches for all objects related to the
'C:' drive object:
using System;
using System.Management;
class Sample_RelationshipQuery
{
public static int Main(string[] args) {
RelationshipQuery query =
new RelationshipQuery("references of {Win32_LogicalDisk.DeviceID='C:'}");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(query);
foreach (ManagementObject assoc in searcher.Get()) {
Console.WriteLine("Association class = " + assoc["__CLASS"]);
}
return 0;
}
}
Imports System
Imports System.Management
Class Sample_RelatedObjectQuery
Overloads Public Shared Function Main(args() As String) As Integer
Dim query As New RelationshipQuery("references of {Win32_LogicalDisk.DeviceID='C:'}")
Dim searcher As New ManagementObjectSearcher(query)
Dim assoc As ManagementObject
For Each assoc In searcher.Get()
Console.WriteLine("Association class = " & assoc("__CLASS"))
Next assoc
Return 0
End Function
End Class
Initializes a new instance
of the class.
Initializes a new instance of the class. This is the default constructor.
Initializes a new instance of the class. If the specified string can be succesfully parsed as
a WQL query, it is considered to be the query string; otherwise, it is assumed to be the path of the source
object for the query. In this case, the query is assumed to be an instances query.
The query string or the class name for this query.
This example shows the two different ways to use this constructor:
//Full query string is specified to the constructor
RelationshipQuery q = new RelationshipQuery("references of {Win32_ComputerSystem.Name='mymachine'}");
//Only the object of interest is specified to the constructor
RelationshipQuery q = new RelationshipQuery("Win32_Service.Name='Alerter'");
'Full query string is specified to the constructor
Dim q As New RelationshipQuery("references of {Win32_ComputerSystem.Name='mymachine'}")
'Only the object of interest is specified to the constructor
Dim q As New RelationshipQuery("Win32_Service.Name='Alerter'")
Initializes a new instance of the class for the given source object and relationship class.
The query is assumed to be an instance query (as opposed to a schema query).
The path of the source object for this query.
The type of relationship for which to query.
Initializes a new instance of the class for the given set of parameters.
The query is assumed to be an instance query (as opposed to a schema query).
The path of the source object for this query.
The type of relationship for which to query.
A qualifier required to be present on the relationship object.
The role that the source object is required to play in the relationship.
When this method returns, it contains a boolean that indicates that only class definitions for the resulting objects are returned.
Initializes a new instance of the class for a schema query using the given set
of parameters. This constructor is used for schema queries only, so the first
parameter must be
.
to indicate that this is a schema query; otherwise, .
The path of the source class for this query.
The type of relationship for which to query.
A qualifier required to be present on the relationship class.
The role that the source class is required to play in the relationship.
Gets or sets a value indicating whether this query is a schema query or an instance query.
if this query
should be evaluated over the schema; if the query should
be evaluated over instances.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new query type.
Gets or sets the source object for this query.
A string representing the path of
the object to be used for the query.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new source object.
Gets or sets the class of the relationship objects wanted in the query.
A string containing the relationship
class name.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new class.
Gets or sets a qualifier required on the relationship objects.
A string containing the name of the
qualifier required on the relationship objects.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new qualifier.
Gets or sets the role of the source object in the relationship.
A string containing the role of this
object.
Setting this property value overrides any
previous value stored in the object. The query string is
rebuilt to reflect the new role.
Gets or sets a value indicating that only the class definitions of the relevant relationship objects be returned.
if the query requests only class definitions of the
result set; otherwise, .
Setting this property value overrides any previous
value stored in the object. As a side-effect, the query string is
rebuilt to reflect the new flag.
Builds the query string according to the current property values.
Parses the query string and sets the property values accordingly.
The query string to be parsed.
Creates a copy of the object.
The copied object.
Represents a WMI event query in WQL format.
using System;
using System.Management;
// This sample demonstrates how to subscribe to an event
// using a WQL event query.
class Sample_EventQuery
{
public static int Main(string[] args)
{
//For this example, we make sure we have an arbitrary class on root\default
ManagementClass newClass = new ManagementClass(
"root\\default",
String.Empty,
null);
newClass["__Class"] = "TestWql";
newClass.Put();
//Create a query object for watching for class deletion events
WqlEventQuery eventQuery = new WqlEventQuery("select * from __classdeletionevent");
//Initialize an event watcher object with this query
ManagementEventWatcher watcher = new ManagementEventWatcher(
new ManagementScope("root/default"),
eventQuery);
//Set up a handler for incoming events
MyHandler handler = new MyHandler();
watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
//Start watching for events
watcher.Start();
//For this example, we delete the class to trigger an event
newClass.Delete();
//Nothing better to do - we loop to wait for an event to arrive.
while (!handler.IsArrived) {
System.Threading.Thread.Sleep(1000);
}
//In this example we only want to wait for one event, so we can stop watching
watcher.Stop();
return 0;
}
public class MyHandler
{
private bool isArrived = false;
//Handles the event when it arrives
public void Arrived(object sender, EventArrivedEventArgs e) {
ManagementBaseObject eventArg = (ManagementBaseObject)(e.NewEvent["TargetClass"]);
Console.WriteLine("Class Deleted = " + eventArg["__CLASS"]);
isArrived = true;
}
//Used to determine whether the event has arrived or not.
public bool IsArrived {
get {
return isArrived;
}
}
}
}
Imports System
Imports System.Management
' This sample demonstrates how to subscribe an event
' using a WQL event query.
Class Sample_EventQuery
Public Shared Sub Main()
'For this example, we make sure we have an arbitrary class on root\default
Dim newClass As New ManagementClass( _
"root\default", _
String.Empty, Nothing)
newClass("__Class") = "TestWql"
newClass.Put()
'Create a query object for watching for class deletion events
Dim eventQuery As New WqlEventQuery("select * from __classdeletionevent")
'Initialize an event watcher object with this query
Dim watcher As New ManagementEventWatcher( _
New ManagementScope("root/default"), _
eventQuery)
'Set up a handler for incoming events
Dim handler As New MyHandler()
AddHandler watcher.EventArrived, AddressOf handler.Arrived
'Start watching for events
watcher.Start()
'For this example, we delete the class to trigger an event
newClass.Delete()
'Nothing better to do - we loop to wait for an event to arrive.
While Not handler.IsArrived
Console.Write("0")
System.Threading.Thread.Sleep(1000)
End While
'In this example we only want to wait for one event, so we can stop watching
watcher.Stop()
End Sub
Public Class MyHandler
Private _isArrived As Boolean = False
'Handles the event when it arrives
Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
Dim eventArg As ManagementBaseObject = CType( _
e.NewEvent("TargetClass"), _
ManagementBaseObject)
Console.WriteLine(("Class Deleted = " + eventArg("__CLASS")))
_isArrived = True
End Sub
'Used to determine whether the event has arrived or not.
Public ReadOnly Property IsArrived() As Boolean
Get
Return _isArrived
End Get
End Property
End Class
End Class
Initializes a new instance of the class.
Initializes a new instance of the
class. This is the default
constructor.
Initializes a new instance of the
class based on the given
query string or event class name.
The string representing either the entire event query or the name of the event class to query. The object will try to parse the string as a valid event query. If unsuccessful, the parser will assume that the parameter represents an event class name.
The two options below are equivalent :
//Full query string specified to the constructor
WqlEventQuery q = new WqlEventQuery("SELECT * FROM MyEvent");
//Only relevant event class name specified to the constructor
WqlEventQuery q = new WqlEventQuery("MyEvent"); //results in the same query as above.
'Full query string specified to the constructor
Dim q As New WqlEventQuery("SELECT * FROM MyEvent")
'Only relevant event class name specified to the constructor
Dim q As New WqlEventQuery("MyEvent") 'results in the same query as above
Initializes a new instance of the
class for the
specified event class name, with the specified condition.
The name of the event class to query.
The condition to apply to events of the specified class.
This example shows how to create an event query that contains a condition in
addition to the event class :
//Requests all "MyEvent" events where the event's properties
//match the specified condition
WqlEventQuery q = new WqlEventQuery("MyEvent", "FirstProp < 20 and SecondProp = 'red'");
'Requests all "MyEvent" events where the event's properties
'match the specified condition
Dim q As New WqlEventQuery("MyEvent", "FirstProp < 20 and SecondProp = 'red'")
Initializes a new instance of the
class for the specified
event class, with the specified latency time.
The name of the event class to query.
A timespan value specifying the latency acceptable for receiving this event. This value is used in cases where there is no explicit event provider for the query requested, and WMI is required to poll for the condition. This interval is the maximum amount of time that can pass before notification of an event must be delivered.
This example shows creating an event query that contains
a
time interval.
//Requests all instance creation events, with a specified latency of
//10 seconds. The query created is "SELECT * FROM __InstanceCreationEvent WITHIN 10"
WqlEventQuery q = new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0,0,10));
'Requests all instance creation events, with a specified latency of
'10 seconds. The query created is "SELECT * FROM __InstanceCreationEvent WITHIN 10"
Dim t As New TimeSpan(0,0,10)
Dim q As New WqlEventQuery("__InstanceCreationEvent", t)
Initializes a new instance of the
class with the specified
event class name, polling interval, and condition.
The name of the event class to query.
A timespan value specifying the latency acceptable for receiving this event. This value is used in cases where there is no explicit event provider for the query requested and WMI is required to poll for the condition. This interval is the maximum amount of time that can pass before notification of an event must be delivered.
The condition to apply to events of the specified class.
This example creates the event query: "SELECT * FROM
WITHIN 10 WHERE
ISA ", which means
"send notification of the creation of
instances,
with a 10-second polling interval."
//Requests notification of the creation of Win32_Service instances with a 10 second
//allowed latency.
WqlEventQuery q = new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0,0,10),
"TargetInstance isa 'Win32_Service'");
'Requests notification of the creation of Win32_Service instances with a 10 second
'allowed latency.
Dim t As New TimeSpan(0,0,10)
Dim q As New WqlEventQuery("__InstanceCreationEvent", _
t, _
"TargetInstance isa ""Win32_Service""")
Initializes a new instance of the
class with the specified
event class name, condition, and grouping interval.
The name of the event class to query.
The condition to apply to events of the specified class.
The specified interval at which WMI sends one aggregate event, rather than many events.
This example creates the event query: "SELECT * FROM
WHERE = 5
GROUP WITHIN 10", which means "send notification of events of type
, in which the
is equal to 5, but send an aggregate event in
a
10-second interval."
//Sends an aggregate of the requested events every 10 seconds
WqlEventQuery q = new WqlEventQuery("FrequentEvent",
"InterestingProperty = 5",
new TimeSpan(0,0,10));
'Sends an aggregate of the requested events every 10 seconds
Dim t As New TimeSpan(0,0,10)
Dim q As New WqlEventQuery("FrequentEvent", _
"InterestingProperty = 5", _
t)
Initializes a new instance of the
class with the specified event class
name, condition, grouping interval, and grouping properties.
The name of the event class to query.
The condition to apply to events of the specified class.
The specified interval at which WMI sends one aggregate event, rather than many events.
The properties in the event class by which the events should be grouped.
This example creates the event query: "SELECT * FROM
WHERE = 'MyBoss' GROUP
WITHIN 300 BY ", which means "send notification when
new email from a particular sender has arrived within the last 10 minutes,
combined with other events that have the same value in the
property."
//Requests "EmailEvent" events where the Sender property is "MyBoss", and
//groups them based on importance
String[] props = {"Importance"};
WqlEventQuery q = new WqlEventQuery("EmailEvent",
"Sender = 'MyBoss'",
new TimeSpan(0,10,0),
props);
'Requests "EmailEvent" events where the Sender property is "MyBoss", and
'groups them based on importance
Dim props() As String = {"Importance"}
Dim t As New TimeSpan(0,10,0)
Dim q As New WqlEventQuery("EmailEvent", _
"Sender = ""MyBoss""", _
t, _
props)
Initializes a new instance of the
class with the specified event class
name, condition, grouping interval, grouping properties, and specified number of events.
The name of the event class on which to be queried.
A timespan value specifying the latency acceptable for receiving this event. This value is used in cases where there is no explicit event provider for the query requested, and WMI is required to poll for the condition. This interval is the maximum amount of time that can pass before notification of an event must be delivered.
The condition to apply to events of the specified class.
The specified interval at which WMI sends one aggregate event, rather than many events.
The properties in the event class by which the events should be grouped.
The condition to apply to the number of events.
This example creates the event query: "SELECT * FROM
WHERE
ISA GROUP WITHIN 300 BY
HAVING
> 15" which means "deliver aggregate events
only if the number of events received from the
same source exceeds 15."
//Requests sending aggregated events if the number of events exceeds 15.
String[] props = {"TargetInstance.SourceName"};
WqlEventQuery q = new WqlEventQuery("__InstanceCreationEvent",
"TargetInstance isa 'Win32_NTLogEvent'",
new TimeSpan(0,10,0),
props,
"NumberOfEvents >15");
'Requests sending aggregated events if the number of events exceeds 15.
Dim props() As String = {"TargetInstance.SourceName"};
Dim t As New TimeSpan(0,10,0)
Dim q As WqlEventQuery("__InstanceCreationEvent", _
"TargetInstance isa ""Win32_NTLogEvent""", _
t, _
props, _
"NumberOfEvents >15")
Gets or sets the language of the query.
The value of this property in this
object is always "WQL".
Gets or sets the string representing the query.
A string representing the query.
Gets or sets the event class to query.
A string containing the name of the
event class to query.
Setting this property value overrides any previous value
stored
in the object. The query string is rebuilt to
reflect the new class name.
This example creates a new
that represents the query: "SELECT * FROM ".
WqlEventQuery q = new WqlEventQuery();
q.EventClassName = "MyEvent";
Dim q As New WqlEventQuery()
q.EventClassName = "MyEvent"
Gets or sets the condition to be applied to events of the
specified class.
The condition is represented as a
string, containing one or more clauses of the form: <propName>
<operator> <value> combined with and/or operators. <propName>
must represent a property defined on the event class specified in this query.
Setting this property value overrides any previous value
stored in the object. The query string is rebuilt to
reflect the new condition.
This example creates a new
that represents the query: "SELECT * FROM WHERE
> 8".
WqlEventQuery q = new WqlEventQuery();
q.EventClassName = "MyEvent";
q.Condition = "PropVal > 8";
Dim q As New WqlEventQuery()
q.EventClassName = "MyEvent"
q.Condition = "PropVal > 8"
Gets or sets the polling interval to be used in this query.
Null, if there is no polling involved; otherwise, a
valid
value if polling is required.
This property should only be set in cases
where there is no event provider for the event requested, and WMI is required to
poll for the requested condition.
Setting this property value overrides any previous value
stored in
the object. The query string is rebuilt to reflect the new interval.
This example creates a new
that represents the query: "SELECT * FROM WITHIN 10 WHERE > 8".
WqlEventQuery q = new WqlEventQuery();
q.EventClassName = "__InstanceModificationEvent";
q.Condition = "PropVal > 8";
q.WithinInterval = new TimeSpan(0,0,10);
Dim q As New WqlEventQuery()
q.EventClassName = "__InstanceModificationEvent"
q.Condition = "PropVal > 8"
q.WithinInterval = New TimeSpan(0,0,10)
Gets or sets the interval to be used for grouping events of
the same type.
Null, if there is no
grouping involved; otherwise, the interval in which WMI should group events of
the same type.
Setting this property value overrides any previous value stored in
the object. The query string is rebuilt to reflect the new interval.
This example creates a new
that represents the query: "SELECT * FROM WHERE
> 8 GROUP WITHIN 10", which means "send notification
of all events where the
property is greater than 8, and aggregate these events within 10-second intervals."
WqlEventQuery q = new WqlEventQuery();
q.EventClassName = "MyEvent";
q.Condition = "PropVal > 8";
q.GroupWithinInterval = new TimeSpan(0,0,10);
Dim q As New WqlEventQuery()
q.EventClassName = "MyEvent"
q.Condition = "PropVal > 8"
q.GroupWithinInterval = New TimeSpan(0,0,10)
Gets or sets properties in the event to be used for
grouping events of the same type.
Null, if no grouping is required; otherwise, a collection of event
property names.
Setting this property value overrides any previous value stored in
the object. The query string is rebuilt to reflect the new grouping.
This example creates a new
that represents the query: "SELECT * FROM GROUP
WITHIN 300 BY ", which means "send notification of all
events, aggregated by the property, within 10-minute intervals."
WqlEventQuery q = new WqlEventQuery();
q.EventClassName = "EmailEvent";
q.GroupWithinInterval = new TimeSpan(0,10,0);
q.GroupByPropertyList = new StringCollection();
q.GroupByPropertyList.Add("Sender");
Dim q As New WqlEventQuery()
q.EventClassName = "EmailEvent"
q.GroupWithinInterval = New TimeSpan(0,10,0)
q.GroupByPropertyList = New StringCollection()
q.GroupByPropertyList.Add("Sender")
Gets or sets the condition to be applied to the aggregation of
events, based on the number of events received.
Null, if no aggregation or no condition should be applied;
otherwise, a condition of the form "NumberOfEvents <operator>
<value>".
Setting this property value overrides any previous value stored in
the object. The query string is rebuilt to reflect the new grouping condition.
This example creates a new
that represents the query: "SELECT * FROM GROUP
WITHIN 300 HAVING > 5", which means "send
notification of all events, aggregated within
10-minute intervals, if there are more than 5 occurrences."
WqlEventQuery q = new WqlEventQuery();
q.EventClassName = "EmailEvent";
q.GroupWithinInterval = new TimeSpan(0,10,0);
q.HavingCondition = "NumberOfEvents > 5";
Dim q As New WqlEventQuery()
q.EventClassName = "EmailEvent"
q.GroupWithinInterval = new TimeSpan(0,10,0)
q.HavingCondition = "NumberOfEvents > 5"
Builds the query string according to the current property values.
Parses the query string and sets the property values accordingly.
The query string to be parsed.
Creates a copy of the object.
The copied object.
Converts a String to a ManagementQuery
Determines if this converter can convert an object in the given source type to the native type of the converter.
An ITypeDescriptorContext that provides a format context.
A Type that represents the type you wish to convert from.
true if this converter can perform the conversion; otherwise, false.
Gets a value indicating whether this converter can convert an object to the given destination type using the context.
An ITypeDescriptorContext that provides a format context.
A Type that represents the type you wish to convert to.
true if this converter can perform the conversion; otherwise, false.
Converts the given object to another type. The most common types to convert
are to and from a string object. The default implementation will make a call
to ToString on the object if the object is valid and if the destination
type is string. If this cannot convert to the desitnation type, this will
throw a NotSupportedException.
An ITypeDescriptorContext that provides a format context.
A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.
The Object to convert.
The Type to convert the value parameter to.
An Object that represents the converted value.
Represents a scope for management operations. In v1.0 the scope defines the WMI namespace in which management operations are performed.
using System;
using System.Management;
// This sample demonstrates how to connect to root/default namespace
// using ManagmentScope object.
class Sample_ManagementScope
{
public static int Main(string[] args)
{
ManagementScope scope = new ManagementScope("root\\default");
scope.Connect();
ManagementClass newClass = new ManagementClass(
scope,
new ManagementPath(),
null);
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to connect to root/default namespace
' using ManagmentScope object.
Class Sample_ManagementScope
Overloads Public Shared Function Main(args() As String) As Integer
Dim scope As New ManagementScope("root\default")
scope.Connect()
Dim newClass As New ManagementClass(scope, _
New ManagementPath(), _
Nothing)
Return 0
End Function
End Class
Gets or sets a value indicating whether the is currently bound to a
WMI server and namespace.
if a connection is alive (bound
to a server and namespace); otherwise, .
A scope is disconnected after creation until someone
explicitly calls (), or uses the scope for any
operation that requires a live connection. Also, the scope is
disconnected from the previous connection whenever the identifying properties of the scope are
changed.
Initializes a new instance
of the class.
Initializes a new instance of the class, with default values. This is the
default constructor.
If the object doesn't have any
properties set before connection, it will be initialized with default values
(for example, the local machine and the root\cimv2 namespace).
ManagementScope s = new ManagementScope();
Dim s As New ManagementScope()
Initializes a new instance of the class representing
the specified scope path.
A containing the path to a server and namespace for the .
ManagementScope s = new ManagementScope(new ManagementPath("\\\\MyServer\\root\\default"));
Dim p As New ManagementPath("\\MyServer\root\default")
Dim s As New ManagementScope(p)
Initializes a new instance of the class representing the specified scope
path.
The server and namespace path for the .
ManagementScope s = new ManagementScope("\\\\MyServer\\root\\default");
Dim s As New ManagementScope("\\MyServer\root\default")
Initializes a new instance of the class representing the specified scope path,
with the specified options.
The server and namespace for the .
A containing options for the connection.
ConnectionOptions opt = new ConnectionOptions();
opt.Username = "Me";
opt.Password = "MyPassword";
ManagementScope s = new ManagementScope("\\\\MyServer\\root\\default", opt);
Dim opt As New ConnectionOptions()
opt.Username = "Me"
opt.Password = "MyPassword"
Dim s As New ManagementScope("\\MyServer\root\default", opt);
Initializes a new instance of the class representing the specified scope path,
with the specified options.
A containing the path to the server and namespace for the .
The containing options for the connection.
ConnectionOptions opt = new ConnectionOptions();
opt.Username = "Me";
opt.Password = "MyPassword";
ManagementPath p = new ManagementPath("\\\\MyServer\\root\\default");
ManagementScope = new ManagementScope(p, opt);
Dim opt As New ConnectionOptions()
opt.UserName = "Me"
opt.Password = "MyPassword"
Dim p As New ManagementPath("\\MyServer\root\default")
Dim s As New ManagementScope(p, opt)
Gets or sets options for making the WMI connection.
The valid
containing options for the WMI connection.
//This constructor creates a scope object with default options
ManagementScope s = new ManagementScope("root\\MyApp");
//Change default connection options -
//In this example, set the system privileges to enabled for operations that require system privileges.
s.Options.EnablePrivileges = true;
'This constructor creates a scope object with default options
Dim s As New ManagementScope("root\\MyApp")
'Change default connection options -
'In this example, set the system privileges to enabled for operations that require system privileges.
s.Options.EnablePrivileges = True
Gets or sets the path for the .
A containing
the path to a server and namespace.
ManagementScope s = new ManagementScope();
s.Path = new ManagementPath("root\\MyApp");
Dim s As New ManagementScope()
s.Path = New ManagementPath("root\MyApp")
Returns a copy of the object.
A new copy of the .
Clone a copy of this object.
A new copy of this object.
object.
Connects this to the actual WMI
scope.
This method is called implicitly when the
scope is used in an operation that requires it to be connected. Calling it
explicitly allows the user to control the time of connection.
ManagementScope s = new ManagementScope("root\\MyApp");
//Explicit call to connect the scope object to the WMI namespace
s.Connect();
//The following doesn't do any implicit scope connections because s is already connected.
ManagementObject o = new ManagementObject(s, "Win32_LogicalDisk='C:'", null);
Dim s As New ManagementScope("root\\MyApp")
'Explicit call to connect the scope object to the WMI namespace
s.Connect()
'The following doesn't do any implicit scope connections because s is already connected.
Dim o As New ManagementObject(s, "Win32_LogicalDisk=""C:""", null)
Converts a String to a ManagementScope
Determines if this converter can convert an object in the given source type to the native type of the converter.
An ITypeDescriptorContext that provides a format context.
A Type that represents the type you wish to convert from.
true if this converter can perform the conversion; otherwise, false.
Gets a value indicating whether this converter can convert an object to the given destination type using the context.
An ITypeDescriptorContext that provides a format context.
A Type that represents the type you wish to convert to.
true if this converter can perform the conversion; otherwise, false.
Converts the given object to another type. The most common types to convert
are to and from a string object. The default implementation will make a call
to ToString on the object if the object is valid and if the destination
type is string. If this cannot convert to the desitnation type, this will
throw a NotSupportedException.
An ITypeDescriptorContext that provides a format context.
A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.
The Object to convert.
The Type to convert the value parameter to.
An Object that represents the converted value.
Contains information about a WMI method.
using System;
using System.Management;
// This example shows how to obtain meta data
// about a WMI method with a given name in a given WMI class
class Sample_MethodData
{
public static int Main(string[] args) {
// Get the "SetPowerState" method in the Win32_LogicalDisk class
ManagementClass diskClass = new ManagementClass("win32_logicaldisk");
MethodData m = diskClass.Methods["SetPowerState"];
// Get method name (albeit we already know it)
Console.WriteLine("Name: " + m.Name);
// Get the name of the top-most class where this specific method was defined
Console.WriteLine("Origin: " + m.Origin);
// List names and types of input parameters
ManagementBaseObject inParams = m.InParameters;
foreach (PropertyData pdata in inParams.Properties) {
Console.WriteLine();
Console.WriteLine("InParam_Name: " + pdata.Name);
Console.WriteLine("InParam_Type: " + pdata.Type);
}
// List names and types of output parameters
ManagementBaseObject outParams = m.OutParameters;
foreach (PropertyData pdata in outParams.Properties) {
Console.WriteLine();
Console.WriteLine("OutParam_Name: " + pdata.Name);
Console.WriteLine("OutParam_Type: " + pdata.Type);
}
return 0;
}
}
Imports System
Imports System.Management
' This example shows how to obtain meta data
' about a WMI method with a given name in a given WMI class
Class Sample_ManagementClass
Overloads Public Shared Function Main(args() As String) As Integer
' Get the "SetPowerState" method in the Win32_LogicalDisk class
Dim diskClass As New ManagementClass("Win32_LogicalDisk")
Dim m As MethodData = diskClass.Methods("SetPowerState")
' Get method name (albeit we already know it)
Console.WriteLine("Name: " & m.Name)
' Get the name of the top-most class where
' this specific method was defined
Console.WriteLine("Origin: " & m.Origin)
' List names and types of input parameters
Dim inParams As ManagementBaseObject
inParams = m.InParameters
Dim pdata As PropertyData
For Each pdata In inParams.Properties
Console.WriteLine()
Console.WriteLine("InParam_Name: " & pdata.Name)
Console.WriteLine("InParam_Type: " & pdata.Type)
Next pdata
' List names and types of output parameters
Dim outParams As ManagementBaseObject
outParams = m.OutParameters
For Each pdata in outParams.Properties
Console.WriteLine()
Console.WriteLine("OutParam_Name: " & pdata.Name)
Console.WriteLine("OutParam_Type: " & pdata.Type)
Next pdata
Return 0
End Function
End Class
Gets or sets the name of the method.
The name of the method.
Gets or sets the input parameters to the method. Each
parameter is described as a property in the object. If a parameter is both in
and out, it appears in both the and
properties.
A
containing all the input parameters to the
method.
Each parameter in the object should have an
qualifier, identifying the order of the parameters in the method call.
Gets or sets the output parameters to the method. Each
parameter is described as a property in the object. If a parameter is both in
and out, it will appear in both the and
properties.
A containing all the output parameters to the method.
Each parameter in this object should have an
qualifier to identify the
order of the parameters in the method call.
The ReturnValue property is a special property of
the
object and
holds the return value of the method.
Gets the name of the management class in which the method was first
introduced in the class inheritance hierarchy.
A string representing the originating
management class name.
Gets a collection of qualifiers defined in the
method. Each element is of type
and contains information such as the qualifier name, value, and
flavor.
A containing the
qualifiers for this method.
Represents the set of methods available in the collection.
using System;
using System.Management;
// This sample demonstrates enumerate all methods in a ManagementClass object.
class Sample_MethodDataCollection
{
public static int Main(string[] args) {
ManagementClass diskClass = new ManagementClass("win32_logicaldisk");
MethodDataCollection diskMethods = diskClass.Methods;
foreach (MethodData method in diskMethods) {
Console.WriteLine("Method = " + method.Name);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates enumerate all methods in a ManagementClass object.
Class Sample_MethodDataCollection
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("win32_logicaldisk")
Dim diskMethods As MethodDataCollection = diskClass.Methods
Dim method As MethodData
For Each method In diskMethods
Console.WriteLine("Method = " & method.Name)
Next method
Return 0
End Function
End Class
Represents the number of objects in the .
The number of objects in the .
Indicates whether the object is synchronized.
if the object is synchronized;
otherwise, .
Represents the object to be used for synchronization.
The object to be used for synchronization.
Copies the into an array.
Copies the into an array.
The array to which to copy the collection.
The index from which to start.
Copies the to a specialized
array.
The destination array to which to copy the objects.
The index in the destination array from which to start the copy.
Returns an enumerator for the .
Each call to this method
returns a new enumerator on the collection. Multiple enumerators can be obtained
for the same method collection. However, each enumerator takes a snapshot
of the collection, so changes made to the collection after the enumerator was
obtained are not reflected.
An to enumerate through the collection.
Represents the enumerator for
objects in the .
using System;
using System.Management;
// This sample demonstrates how to enumerate all methods in
// Win32_LogicalDisk class using MethodDataEnumerator object.
class Sample_MethodDataEnumerator
{
public static int Main(string[] args)
{
ManagementClass diskClass = new ManagementClass("win32_logicaldisk");
MethodDataCollection.MethodDataEnumerator diskEnumerator =
diskClass.Methods.GetEnumerator();
while(diskEnumerator.MoveNext())
{
MethodData method = diskEnumerator.Current;
Console.WriteLine("Method = " + method.Name);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to enumerate all methods in
' Win32_LogicalDisk class using MethodDataEnumerator object.
Class Sample_MethodDataEnumerator
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("win32_logicaldisk")
Dim diskEnumerator As _
MethodDataCollection.MethodDataEnumerator = _
diskClass.Methods.GetEnumerator()
While diskEnumerator.MoveNext()
Dim method As MethodData = diskEnumerator.Current
Console.WriteLine("Method = " & method.Name)
End While
Return 0
End Function
End Class
Returns the current in the
enumeration.
The current item in the collection.
Moves to the next element in the enumeration.
if the enumerator was successfully advanced to the next method; if the enumerator has passed the end of the collection.
Resets the enumerator to the beginning of the enumeration.
Returns the specified from the .
The name of the method requested.
A instance containing all information about the specified method.
Removes a from the .
The name of the method to remove from the collection.
Removing objects from the
can only be done when the class has no
instances. Any other case will result in an exception.
Adds a to the .
Adds a to the . This overload will
add a new method with no parameters to the collection.
The name of the method to add.
Adding objects to the can only
be done when the class has no instances. Any other case will result in an
exception.
Adds a to the . This overload will add a new method with the
specified parameter objects to the collection.
The name of the method to add.
The holding the input parameters to the method.
The holding the output parameters to the method.
Adding objects to the can only be
done when the class has no instances. Any other case will result in an
exception.
Represents information about a WMI property.
using System;
using System.Management;
// This sample displays all properties that qualifies the "DeviceID" property
// in Win32_LogicalDisk.DeviceID='C' instance.
class Sample_PropertyData
{
public static int Main(string[] args) {
ManagementObject disk =
new ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"");
PropertyData diskProperty = disk.Properties["DeviceID"];
Console.WriteLine("Name: " + diskProperty.Name);
Console.WriteLine("Type: " + diskProperty.Type);
Console.WriteLine("Value: " + diskProperty.Value);
Console.WriteLine("IsArray: " + diskProperty.IsArray);
Console.WriteLine("IsLocal: " + diskProperty.IsLocal);
Console.WriteLine("Origin: " + diskProperty.Origin);
return 0;
}
}
Imports System
Imports System.Management
' This sample displays all properties that qualifies the "DeviceID" property
' in Win32_LogicalDisk.DeviceID='C' instance.
Class Sample_PropertyData
Overloads Public Shared Function Main(args() As String) As Integer
Dim disk As New ManagementObject("Win32_LogicalDisk.DeviceID=""C:""")
Dim diskProperty As PropertyData = disk.Properties("DeviceID")
Console.WriteLine("Name: " & diskProperty.Name)
Console.WriteLine("Type: " & diskProperty.Type)
Console.WriteLine("Value: " & diskProperty.Value)
Console.WriteLine("IsArray: " & diskProperty.IsArray)
Console.WriteLine("IsLocal: " & diskProperty.IsLocal)
Console.WriteLine("Origin: " & diskProperty.Origin)
Return 0
End Function
End Class
Gets or sets the name of the property.
A string containing the name of the
property.
Gets or sets the current value of the property.
An object containing the value of the
property.
Gets or sets the CIM type of the property.
A value
representing the CIM type of the property.
Gets or sets a value indicating whether the property has been defined in the current WMI class.
if the property has been defined
in the current WMI class; otherwise, .
Gets or sets a value indicating whether the property is an array.
if the property is an array; otherwise, .
Gets or sets the name of the WMI class in the hierarchy in which the property was introduced.
A string containing the name of the
originating WMI class.
Gets or sets the set of qualifiers defined on the property.
A that represents
the set of qualifiers defined on the property.
Takes a property value returned from WMI and maps it to an
appropriate managed code representation.
Takes a managed code value, together with a desired property
Represents the set of properties of a WMI object.
using System;
using System.Management;
// This sample demonstrates how to enumerate properties
// in a ManagementObject object.
class Sample_PropertyDataCollection
{
public static int Main(string[] args) {
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid = \"c:\"");
PropertyDataCollection diskProperties = disk.Properties;
foreach (PropertyData diskProperty in diskProperties) {
Console.WriteLine("Property = " + diskProperty.Name);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to enumerate properties
' in a ManagementObject object.
Class Sample_PropertyDataCollection
Overloads Public Shared Function Main(args() As String) As Integer
Dim disk As New ManagementObject("win32_logicaldisk.deviceid=""c:""")
Dim diskProperties As PropertyDataCollection = disk.Properties
Dim diskProperty As PropertyData
For Each diskProperty In diskProperties
Console.WriteLine("Property = " & diskProperty.Name)
Next diskProperty
Return 0
End Function
End Class
Gets or sets the number of objects in the .
The number of objects in the collection.
Gets or sets a value indicating whether the object is synchronized.
if the object is synchronized;
otherwise, .
Gets or sets the object to be used for synchronization.
The object to be used for synchronization.
Copies the into an array.
Copies the into an array.
The array to which to copy the .
The index from which to start copying.
Copies the to a specialized object
array.
The destination array to contain the copied .
The index in the destination array from which to start copying.
Returns the enumerator for this .
An
that can be used to iterate through the collection.
Represents the enumerator for
objects in the .
using System;
using System.Management;
// This sample demonstrates how to enumerate all properties in a
// ManagementObject using the PropertyDataEnumerator object.
class Sample_PropertyDataEnumerator
{
public static int Main(string[] args) {
ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID='C:'");
PropertyDataCollection.PropertyDataEnumerator propertyEnumerator = disk.Properties.GetEnumerator();
while(propertyEnumerator.MoveNext()) {
PropertyData p = (PropertyData)propertyEnumerator.Current;
Console.WriteLine("Property found: " + p.Name);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to enumerate all properties in a
' ManagementObject using PropertyDataEnumerator object.
Class Sample_PropertyDataEnumerator
Overloads Public Shared Function Main(args() As String) As Integer
Dim disk As New ManagementObject("Win32_LogicalDisk.DeviceID='C:'")
Dim propertyEnumerator As _
PropertyDataCollection.PropertyDataEnumerator = disk.Properties.GetEnumerator()
While propertyEnumerator.MoveNext()
Dim p As PropertyData = _
CType(propertyEnumerator.Current, PropertyData)
Console.WriteLine("Property found: " & p.Name)
End While
Return 0
End Function
End Class
Gets the current in the enumeration.
The current
element in the collection.
Moves to the next element in the
enumeration.
if the enumerator was successfully advanced to the next element;
if the enumerator has passed the end of the collection.
Resets the enumerator to the beginning of the
enumeration.
Returns the specified property from the , using [] syntax.
The name of the property to retrieve.
A , based on
the name specified.
ManagementObject o = new ManagementObject("Win32_LogicalDisk.Name = 'C:'");
Console.WriteLine("Free space on C: drive is: ", c.Properties["FreeSpace"].Value);
Dim o As New ManagementObject("Win32_LogicalDisk.Name=""C:""")
Console.WriteLine("Free space on C: drive is: " & c.Properties("FreeSpace").Value)
Removes a from the .
The name of the property to be removed.
Properties can only be removed from class definitions,
not from instances. This method is only valid when invoked on a property
collection in a .
ManagementClass c = new ManagementClass("MyClass");
c.Properties.Remove("PropThatIDontWantOnThisClass");
Dim c As New ManagementClass("MyClass")
c.Properties.Remove("PropThatIDontWantOnThisClass")
Adds a new with the specified value.
Adds a new with the specified value. The value cannot
be null and must be convertable to a CIM type.
The name of the new property.
The value of the property (cannot be null).
Properties can only be added to class definitions, not
to instances. This method is only valid when invoked on a
in
a .
Adds a new with the specified value and CIM type.
The name of the property.
The value of the property (which can be null).
The CIM type of the property.
Properties can only be added to class definitions, not
to instances. This method is only valid when invoked on a
in
a .
Adds a new with no assigned value.
The name of the property.
The CIM type of the property.
to specify that the property is an array type; otherwise, .
Properties can only be added to class definitions, not
to instances. This method is only valid when invoked on a
in
a .
Contains information about a WMI qualifier.
using System;
using System.Management;
// This sample demonstrates how to enumerate qualifiers
// of a ManagementClass object.
class Sample_QualifierData
{
public static int Main(string[] args) {
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
diskClass.Options.UseAmendedQualifiers = true;
QualifierData diskQualifier = diskClass.Qualifiers["Description"];
Console.WriteLine(diskQualifier.Name + " = " + diskQualifier.Value);
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to enumerate qualifiers
' of a ManagementClass object.
Class Sample_QualifierData
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("win32_logicaldisk")
diskClass.Options.UseAmendedQualifiers = True
Dim diskQualifier As QualifierData = diskClass.Qualifiers("Description")
Console.WriteLine(diskQualifier.Name + " = " + diskQualifier.Value)
Return 0
End Function
End Class
Represents the name of the qualifier.
The name of the qualifier.
Gets or sets the value of the qualifier.
The value of the qualifier.
Qualifiers can only be of the following subset of CIM
types: , ,
, , ,
, , ,
.
Gets or sets a value indicating whether the qualifier is amended.
if this qualifier is amended;
otherwise, .
Amended qualifiers are
qualifiers whose value can be localized through WMI. Localized qualifiers
reside in separate namespaces in WMI and can be merged into the basic class
definition when retrieved.
Gets or sets a value indicating whether the qualifier has been defined locally on
this class or has been propagated from a base class.
if the qualifier has been defined
locally on this class; otherwise, .
Gets or sets a value indicating whether the qualifier should be propagated to instances of the
class.
if this qualifier should be
propagated to instances of the class; otherwise, .
Gets or sets a value indicating whether the qualifier should be propagated to
subclasses of the class.
if the qualifier should be
propagated to subclasses of this class; otherwise, .
Gets or sets a value indicating whether the value of the qualifier can be
overridden when propagated.
if the value of the qualifier
can be overridden when propagated; otherwise, .
Represents a collection of objects.
using System;
using System.Management;
// This sample demonstrates how to list all qualifiers including amended
// qualifiers of a ManagementClass object.
class Sample_QualifierDataCollection
{
public static int Main(string[] args) {
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
diskClass.Options.UseAmendedQualifiers = true;
QualifierDataCollection qualifierCollection = diskClass.Qualifiers;
foreach (QualifierData q in qualifierCollection) {
Console.WriteLine(q.Name + " = " + q.Value);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to list all qualifiers including amended
' qualifiers of a ManagementClass object.
Class Sample_QualifierDataCollection
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("Win32_LogicalDisk")
diskClass.Options.UseAmendedQualifiers = true
Dim qualifierCollection As QualifierDataCollection = diskClass.Qualifiers
Dim q As QualifierData
For Each q In qualifierCollection
Console.WriteLine(q.Name & " = " & q.Value)
Next q
Return 0
End Function
End Class
Return the qualifier set associated with its type
Overload with use of private data member, qualifierType
Return the qualifier set associated with its type
Gets or sets the number of objects in the .
The number of objects in the collection.
Gets or sets a value indicating whether the object is synchronized.
if the object is synchronized;
otherwise, .
Gets or sets the object to be used for synchronization.
The object to be used for synchronization.
Copies the into an array.
Copies the into an array.
The array to which to copy the .
The index from which to start copying.
Copies the into a specialized
array.
The specialized array of objects
to which to copy the .
The index from which to start copying.
Returns an enumerator for the . This method is strongly typed.
An that can be used to iterate through the
collection.
Represents the enumerator for
objects in the .
using System;
using System.Management;
// This sample demonstrates how to enumerate qualifiers of a ManagementClass
// using QualifierDataEnumerator object.
class Sample_QualifierDataEnumerator
{
public static int Main(string[] args) {
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
diskClass.Options.UseAmendedQualifiers = true;
QualifierDataCollection diskQualifier = diskClass.Qualifiers;
QualifierDataCollection.QualifierDataEnumerator
qualifierEnumerator = diskQualifier.GetEnumerator();
while(qualifierEnumerator.MoveNext()) {
Console.WriteLine(qualifierEnumerator.Current.Name + " = " +
qualifierEnumerator.Current.Value);
}
return 0;
}
}
Imports System
Imports System.Management
' This sample demonstrates how to enumerate qualifiers of a ManagementClass
' using QualifierDataEnumerator object.
Class Sample_QualifierDataEnumerator
Overloads Public Shared Function Main(args() As String) As Integer
Dim diskClass As New ManagementClass("win32_logicaldisk")
diskClass.Options.UseAmendedQualifiers = True
Dim diskQualifier As QualifierDataCollection = diskClass.Qualifiers
Dim qualifierEnumerator As _
QualifierDataCollection.QualifierDataEnumerator = _
diskQualifier.GetEnumerator()
While qualifierEnumerator.MoveNext()
Console.WriteLine(qualifierEnumerator.Current.Name & _
" = " & qualifierEnumerator.Current.Value)
End While
Return 0
End Function
End Class
Gets or sets the current in the enumeration.
The current element in the collection.
Moves to the next element in the enumeration.
if the enumerator was successfully advanced to the next
element; if the enumerator has passed the end of the
collection.
Resets the enumerator to the beginning of the enumeration.
Gets the specified from the .
The name of the to access in the .
A , based on the name specified.
Removes a from the by name.
The name of the to remove.
Adds a to the .
Adds a to the . This overload specifies the qualifier name and value.
The name of the to be added to the .
The value for the new qualifier.
Adds a to the . This overload
specifies all property values for a object.
The qualifier name.
The qualifier value.
to specify that this qualifier is amended (flavor); otherwise, .
to propagate this qualifier to instances; otherwise, .
to propagate this qualifier to subclasses; otherwise, .
to specify that this qualifier's value is overridable in instances of subclasses; otherwise, .
Defines the languages supported by the code generator.
A value for generating C# code.
A value for generating JScript code.
A value for generating Visual Basic code.
A value for generating Visual J# code.
A value for generating Managed C++ code.
Used to generate a strongly-typed code class for a given WMI class.
Creates an empty generator object. This is the default constructor.
Creates a generator object and initializes it
with the specified .
object for which the code is to be generated.
Returns a for
this class.
Indicates if a class for handling system properties should be included.
Indicates if the generated code is for a class that handles system properties.
Returns the for the WMI class.
If includeSystemProperties is ,
the ManagementSystemProperties class is included in the generated class definition.
This parameter is ignored if systemPropertyClass is .
Generates a strongly-typed code class for the specified language provider (C#, Visual Basic or JScript)
and writes it to the specified file.
The language to generate in.
The path to the file where the generated code should be stored.
The .NET namespace into which the class is generated.
Checks if mandatory properties are properly initialized.
This function will generate the code. This is the function which
should be called for generating the code.
Flag to indicate if system properties are to be included or not
Function for initializing the class object that will be used to get all the
method and properties of the WMI Class for generating the code.
This functrion initializes the public attributes and private variables
list that will be used in the generated code.
This function will solve the naming collisions that might occur
due to the collision between the local objects of the generated
class and the properties/methos of the original WMI Class.
This function is used to resolve (actually generate a new name) collision
between the generated class properties/variables with WMI methods/properties.
This function safely assumes that there will be atleast one string left
in the series prop0, prop1 ...prop(maxInt) . Otherwise this function will
enter an infinite loop. May be we can avoid this through something, which
i will think about it later
This function processes the WMI namespace and WMI classname and converts them to
the namespace used to generate the class and the classname.
This function generates the code for the read only property.
The generated code will be of the form
public <propType> <propName>{
get {
return (<propValue>);
}
}
Function for generating the helper class "ManagementSystemProperties" which is
used for seperating the system properties from the other properties. This is used
just to make the drop down list in the editor to look good.
This function will enumerate all the properties (except systemproperties)
of the WMI class and will generate them as properties of the managed code
wrapper class.
This function will process the qualifiers for a given WMI property and set the
attributes of the generated property accordingly.
This function will generate enums corresponding to the Values/Valuemap pair
and for the BitValues/Bitmap pair.
returns if the property is an enum. This is checked by if enum is added or not
This function generated the static function which s used to construct the path
private static String ConstructPath(String keyName)
{
//FOR NON SINGLETON CLASSES
String strPath;
strPath = ((("\\<defNamespace>:<defClassName>";
strPath = ((_strPath) + (((".Key1=") + (key_Key1))));
strPath = ((_strPath) + (((",Key2=") + ((("\"") + (((key_Key2) + ("\""))))))));
return strPath;
//FOR SINGLETON CLASS
return "\\<defNameSpace>:<defClassName>=@";
}
This function generates the default constructor.
public Cons() {
_privObject = new ManagementObject();
_privSystemProps = new ManagementSystemProperties(_privObject);
}
This function create the constuctor which accepts the key values.
public cons(UInt32 key_Key1, String key_Key2) :this(null,<ClassName>.ConstructPath(<key1,key2>),null) {
}
This function create the constuctor which accepts a scope and key values.
public cons(ManagementScope scope,UInt32 key_Key1, String key_Key2) :this(scope,<ClassName>.ConstructPath(<key1,key2>),null) {
}
This function generates code for the constructor which accepts ManagementPath as the parameter.
The generated code will look something like this
public Cons(ManagementPath path) : this (null, path,null){
}
This function generates code for the constructor which accepts ManagementPath and GetOptions
as parameters.
The generated code will look something like this
public Cons(ManagementPath path, ObjectGetOptions options) : this (null, path,options){
}
This function generates code for the constructor which accepts Scope as a string, path as a
string and GetOptions().
The generated code will look something like this
public Cons(String scope, String path, ObjectGetOptions options) :
this (new ManagementScope(scope), new ManagementPath(path),options){
}
This function generates code for the constructor which accepts ManagementScope as parameters.
The generated code will look something like this
public Cons(ManagementScope scope, ObjectGetOptions options) : this (scope, <ClassName>.ConstructPath(),null){
}
This function generates code for the constructor which accepts GetOptions
as parameters.
The generated code will look something like this
public Cons(ObjectGetOptions options) : this (null, <ClassName>.ConstructPath(),options){
}
This function generates code for the constructor which accepts ManagementScope and GetOptions
as parameters.
The generated code will look something like this
public Cons(ManagementScope scope, ObjectGetOptions options) : this (scope, <ClassName>.ConstructPath(),options){
}
This function generated the constructor like
public cons(ManagementScope scope, ManagamentPath path,ObjectGetOptions getOptions)
{
PrivateObject = new ManagementObject(scope,path,getOptions);
PrivateSystemProperties = new ManagementSystemProperties(PrivateObject);
}
This function generates code for the constructor which accepts ManagementObject as the parameter.
The generated code will look something like this
public Cons(ManagementObject theObject) {
if (CheckIfProperClass(theObject.Scope, theObject.Path, theObject.Options) = true) {
privObject = theObject;
privSystemProps = new WmiSystemProps(privObject);
curObj = privObject;
}
else {
throw new ArgumentException("Class name doesn't match");
}
}
This function generates code for the constructor which accepts ManagementObject as the parameter.
The generated code will look something like this
public Cons(ManagementBaseObject theObject) {
if (CheckIfProperClass(theObject) = true)
{
embeddedObj = theObject
PrivateSystemProperties = New ManagementSystemProperties(theObject)
curObj = embeddedObj
isEmbedded = true
}
else
{
throw new ArgumentException("Class name doesn't match");
}
}
This function generated the constructor like
public cons(ManagementScope scope, ManagamentPath path,ObjectGetOptions getOptions)
{
PrivateObject = new ManagementObject(scope,path,getOptions);
PrivateSystemProperties = new ManagementSystemProperties(PrivateObject);
}
This function generates the WMI methods as the methods in the generated class.
The generated code will look something like this
public <retType> Method1(<type> param1, <type> param2,...) {
ManagementBaseObject inParams = null;
inParams = _privObject.GetMethodParameters("ChangeStartMode");
inParams["<inparam1>"] = <Value>;
inParams["<inoutparam2>"] = <Value>;
................................
ManagementBaseObject outParams = _privObject.InvokeMethod("ChangeStartMode", inParams, null);
inoutParam3 = (<type>)(outParams.Properties["<inoutParam3>"]);
outParam4 = (String)(outParams.Properties["<outParam4>"]);
................................
return (<retType>)(outParams.Properties["ReturnValue"].Value);
}
The code generated changes if the method is static function
public <retType> Method1(<type> param1, <type> param2,...) {
ManagementBaseObject inParams = null;
ManagementObject classObj = new ManagementObject(null, "WIN32_SHARE", null); // the classname
inParams = classObj.GetMethodParameters("Create");
inParams["<inparam1>"] = <Value>;
inParams["<inoutparam2>"] = <Value>;
................................
ManagementBaseObject outParams = classObj.InvokeMethod("ChangeStartMode", inParams, null);
inoutParam3 = (<type>)(outParams.Properties["<inoutParam3>"]);
outParam4 = (String)(outParams.Properties["<outParam4>"]);
................................
return (<retType>)(outParams.Properties["ReturnValue"].Value);
}
This function returns a Collectionclass for the query
"Select * from <ClassName>"
This is a static method. The output is like this
public static ServiceCollection All()
{
return GetInstances((System.Management.ManagementScope)null,(System.Management.EnumerateionOptions)null);
}
This function will accept the condition and will return collection for the query
"select * from <ClassName> where <condition>"
The generated code will be like
public static ServiceCollection GetInstances(String Condition) {
return GetInstances(null,Condition,null);
}
This function returns the collection for the query
"select <parameterList> from <ClassName>"
The generated output is like
public static ServiceCollection GetInstances(String []selectedProperties) {
return GetInstances(null,null,selectedProperties);
}
This function returns the collection for the query
"select <parameterList> from <ClassName> where <WhereClause>"
The generated output is like
public static ServiceCollection GetInstances(String condition, String []selectedProperties) {
return GetInstances(null,condition,selectedProperties);
}
This function returns a Collectionclass for the query
"Select * from <ClassName>"
This is a static method. The output is like this
public static (ObjectCollection)GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
{
if ((mgmtScope == null))
{
mgmtScope = new System.Management.ManagementScope();
mgmtScope.Path.NamespacePath = "root\\CimV2";
}
System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
pathObj.ClassName = "CIM_LogicalDisk";
pathObj.NamespacePath = "root\\CimV2";
System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
if ((enumOptions == null))
{
enumOptions = new System.Management.EnumerationOptions();
enumOptions.EnsureLocatable = true;
}
return new ObjectCollection(clsObject.GetInstances(enumOptions));
}
This method takes the scope which is useful for connection to remote machine
This function will accept the condition and will return collection for the query
"select * from <ClassName> where <condition>"
The generated code will be like
public static ServiceCollection GetInstances(String Condition) {
return GetInstances(scope,Condition,null);
}
This function returns the collection for the query
"select <parameterList> from <ClassName>"
The generated output is like
public static ServiceCollection GetInstances(String []selectedProperties) {
return GetInstances(scope,null,selectedProperties);
}
This function generates the code like
public static ServiceCollection GetInstances(ManagementScope scope,String Condition, String[] selectedProperties) {
if (scope == null)
{
scope = new ManagementScope();
scope.Path.NamespacePath = WMINamespace;
}
ManagementObjectSearcher ObjectSearcher = new ManagementObjectSearcher(scope,new SelectQuery("Win32_Service",Condition,selectedProperties));
QueryOptions query = new QueryOptions();
query.EnsureLocatable = true;
ObjectSearcher.Options = query;
return new ServiceCollection(ObjectSearcher.Get());
}
This function will add the variable as a private member to the class.
The generated code will look like this
private <MemberType> <MemberName>;
This function will add the variable as a private member to the class.
The generated code will look like this
private <MemberType> <MemberName> = <initValue>;
This function will find a given string in the passed
in a case insensitive manner and will return true if the string is found.
This function will convert the given CIMTYPE to an acceptable .NET type.
Since CLS doen't support lotz of the basic types, we are using .NET helper
classes here. We safely assume that there won't be any problem using them
since .NET has to be there for the System.Management.Dll to work.
This function is used to determine whether the given CIMTYPE can be represented as an integer.
This helper function is mainly used to determine whether this type will be support by enums.
[To be supplied.]
[To be supplied.]
Function to convert a given ValueMap or BitMap name to propert enum name
This function goes thru the names in array list and resolves any duplicates
if any so that these names can be added as values of enum
This function will find a given string in the passed
array list.
Function to create a appropriate generator
Function which checks if the language supports Unsigned numbers
Language
Function which adds commit function to commit all the changes
to the object to WMI
Function to convert a value in format "0x..." to a integer
to the object to WMI
Function to get the Converstion function to be used for Numeric datatypes
Checks if a given property is to be visible for Designer seriliazation
Checks if the given property type is represented as ValueType
Gets the dynamic qualifier on the class to find if the
class is a dynamic class
Converts a numberic value to appropriate type and adds it to array
Adds comments at the beginning of the class defination
Generates code for ManagementClassName Property
Generates the functions CheckIfProperClass() which checks if the given path
can be represented with the generated code
Generates the functions CheckIfProperClass() which checks if the given path
can be represented with the generated code
Generates code for Property Get for Cimtype.Reference and CimType.DateTime type property
Also generated code to initialize a variable after converting a property to DateTime and ManagementPathProperty
Generates code for Property Set for Cimtype.DateTime and CimType.Reference type property
Internal function used to create object. Used in adding code for Property Get for DateTime and Reference properties
Internal function used to create code to convert DateTime or ManagementPath to String
convert a expression. Used in adding code for Property Set for DateTime and Reference properties
This function generates static CreateInstance to create an WMI instance.
public static GenClass CreateInstance() {
return new GenClass(new ManagementClass(new System.Management.ManagementClass(CreatedWmiNamespace, CreatedClassName, null).CreateInstance()));
}
This function generates static CreateInstance to create an WMI instance.
public static GenClass CreateInstance() {
PrivateLateBoundObject.Delete();
}
Function to genreate helper function for DMTF to DateTime and DateTime to DMTF
Function to genreate helper function for DMTF Time interval to TimeSpan and vice versa
Generated code for function to do conversion of date from DMTF format to DateTime format
Generates some common code used in conversion function for DateTime
The ThreadDispatch class allows clients to very easily spawn a thread, specify a worker delegate to be called from the
spawned thread and wait until thread finishes work. This is important in cases where a new thread needs to be spawned but
the main thread has to wait until the spawned thread finishes. As an example of this, in WMI we spawn MTA threads and create
various objects in these threads to make sure we avoid marshaling cost.
If the worker thread returns a value it is stored in the ThreadDispatch object and accessible to clients via the Result property.
Also, any exception thrown is propagated from worker thread to main thread (by rethrowing orinal exception):
ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethod ( Class1.Func ) ) ;
disp.Start ( ) ;
Four different delegate types are supported:
1. Delegate with no parameter and no return value.
2. Delegate with no parameter and return value.
3. Delegate with parameter and no return value.
4. Delegate with parameter and return value.
[Get] Gets the exception associated with the operation performed by thread.
This can be null if no exception has been thrown.
[Get/Set] The parameter to be used by worker thread. This will typically be a 'this' reference for access to instance members.
[Get/Set] The background property of a thread. Defaults to false.
[Get] The result of the worker method called.
[Get/Set] The thread apartment type
Delegate declaration representing signature of worker method with return value.
Delegate declaration representing signature of worker method with return value and parameter.
Delegate declaration representing signature of worker method with no return value and no parameter
Delegate declaration representing signature of worker method with parameter.
Constructs a ThreadDispatch object with the thread worker method.
Default settings on the ThreadDispatch object are:
1. Parameter is null
2. Thread ApartmentState will be MTA
3. Background thread status will be false
Delegate to be called to perform the work
Constructs a ThreadDispatch object with the thread worker method.
Default settings on the ThreadDispatch object are:
1. Parameter is null
2. Thread ApartmentState will be MTA
3. Background thread status will be false
Delegate to be called to perform the work
Constructs a ThreadDispatch object with the thread worker method.
Default settings on the ThreadDispatch object are:
1. Parameter is null
2. Thread ApartmentState will be MTA
3. Background thread status will be false
Delegate to be called to perform the work
Constructs a ThreadDispatch object with the thread worker method.
Default settings on the ThreadDispatch object are:
1. Parameter is null
2. Thread ApartmentState will be MTA
3. Background thread status will be false
Delegate to be called to perform the work
Starts the thread execution and waits for thread to finish. If an exception occurs in the worker method
this method rethrows the exception.
Initializes the ThreadDispatch instance with initial values. Note that this constructor is private to avoid
declaring instances without specifying at least a worker delegate instance.
Initializes the thread state members.
Parameters to be passed to thread
The delegate to be called from thread
The apartment of the thread created
Thread is created as a background or not
Initializes the thread state members.
Parameters to be passed to thread
The delegate to be called from thread
The apartment of the thread created
Thread is created as a background or not
Initializes the thread state members.
Parameters to be passed to thread
The delegate to be called from thread
The apartment of the thread created
Thread is created as a background or not
Initializes the thread state members.
Parameters to be passed to thread
The delegate to be called from thread
The apartment of the thread created
Thread is created as a background or not
Starts the execution of the thread and waits until the threadFinished event is signaled before continuing
Entry point for the newly created thread. This method is wrapped in a try/catch block and captures any
exceptions thrown from the worker method and re-throws the exception.
The worker method for this thread entry point has no parameter and no return value.
Entry point for the newly created thread. This method is wrapped in a try/catch block and captures any
exceptions thrown from the worker method and re-throws the exception.
The worker method for this thread entry point takes a parameter and no return value.
Entry point for the newly created thread. This method is wrapped in a try/catch block and captures any
exceptions thrown from the worker method and re-throws the exception.
The worker method for this thread entry point has no parameter but does return a value.
Entry point for the newly created thread. This method is wrapped in a try/catch block and captures any
exceptions thrown from the worker method and re-throws the exception.
The worker method for this thread entry point has a parameter and return value.
The Query string supplied was invalid or improperly formed
The Query string supplied was invalid because it contains a duplicate token
The Query string supplied was invalid because a supplied token was null
Unable to wakeup the worker thread to create an object in MTA
ClassName not initialized.
Class name does not match.
Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used.
Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property).
An Early Bound class generated for the WMI class.
Below are different overloads of constructors to initialize an instance of the class with a WMI object.
Private property to hold the name of WMI class which created this class.
Private property to hold the WMI namespace in which the class resides.
The current WMI object used
Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa.
Private variable to hold the embedded property representing the instance.
Enumerator implementation for enumerating instances of the class.
Flag to indicate if the instance is an embedded object.
Different overloads of GetInstances() help in enumerating instances of the WMI class.
Functions Is<PropertyName>Null() are used to check if a property is NULL.
Underlying lateBound WMI object.
Property returning the underlying lateBound object.
The ManagementPath of the underlying WMI object.
ManagementScope of the object.
Property returns the namespace of the WMI class.
Member variable to store the 'automatic commit' behavior for the class.
TypeConverter to handle null values for ValueType properties
Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL.
Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to n ...
Private member variable to hold the ManagementScope which is used by the various methods.
Public static scope property which is used by the various methods.
Property pointing to an embedded object to get System properties of the WMI object.
Embedded class to represent WMI system Properties.
Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa.
Converts a given datetime in DMTF format to System.DateTime object.
Converts a given System.DateTime object to DMTF datetime format.
Converts a given System.TimeSpan object to DMTF Time interval format.
Converts a given time interval in DMTF format to System.TimeSpan object.
If the embedded property is strongly typed then, to strongly type the property to the type of
the embedded object, you have to do the following things.
\t1. Generate Managed class for the WMI class of the embedded property. This can be done with MgmtClassGen.exe tool or from Server Explorer.
\t2. Include the namespace of the generated class.
\t3. Change the property get/set functions so as return the instance of the Managed class.
Below is a sample code.
VB Code
C# Code
public <ManagedClassName of Embedded property> <PropertyName>
\t\tIf (AutoCommitProp == true && isEmbedded == false)
\t\t{
\t\t\tPrivateLateBoundObject.Put();
\t\t}
\t}
}
{
\tget
\t{
\t\treturn new <ManagedClassName of Embedded property>((System.Management.ManagementBaseObject)(curObj["<PropertyName>"]));
\t}
\tset
\t{
\t\tcurObj["<PropertyName>"] = value.LateBoundObject;
Public Property <PropertyName>() As <ManagedClassName of Embedded property>
\tEnd Set
\tGet
\t\tReturn New <ManagedClassName of Embedded Property>(CType(curObj("<PropertyName>"),System.Management.ManagementBaseObject))
\tEnd Get
\tSet(ByVal Value As <ManagedClassName of Embedded property>)
\t\tcurObj("EObject")=Value.LateBoundObject
\t\tIf (AutoCommitProp = True And isEmbedded = False) Then
\t\t\tPrivateLateBoundObject.Put()
\t\tEnd If
FilePath cannot be empty.
Namespace not initialized.
FilePath or code generator object is null.
Unable to create code generator for '{0}'
System.Management currently is only supported for Windows desktop applications.
Could not find an installation of .NET Framework v4.0.30319. System.Management requires native modules from the .NET Framework to operate.
Failed to load required native library '{0}'.
The native library '{0}' does not have all required functions. Please, update the .NET Framework.
The Query string supplied was invalid or improperly formed. Token `{0}` is expected