Hi
I am going a bit mad trying to overcome what seems to be a simple task.
I am trying to list the available WMI classes in code. I realise I can look these up in MSDN but need to enumerate them in code. I am trying to find the equivalent of the following vb script in c#
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colClasses = objWMIService.SubclassesOf()
For Each objClass in colClasses
WScript.Echo objClass.Path_.Class
Next
If I execute this using cscript I get exactly what I am after in c#. However, I am finding it impossible to create C# code to provide the same output. Any assistance would be very greatly appreciated
Regards
AhmetPosted Oct 28, 2008, 11:18 AM
AhmetPosted Oct 28, 2008, 7:50 AM
Andy WebsterPosted Sep 11, 2008, 2:32 AM
AlanPosted Sep 10, 2008, 11:00 AM
Sure, Andy.
If you pass a WMI class name at the command line, then this program should enumerate its properties:
using System;
using System.Management;
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Must be exactly one argument");
return;
}
string wmiClassName = args[0].Trim();
ManagementClass wmiClass = new ManagementClass(wmiClassName);
int number;
try
{
number = wmiClass.Properties.Count;
}
catch
{
Console.WriteLine("Class not found");
return;
}
string temp = (number != 1) ? "properties" : "property";
string temp2 = (number != 0) ? "as follows" : "";
Console.Clear();
Console.WriteLine("{0} has {1} {2} {3}\n", wmiClassName, number, temp, temp2);
int count = 0;
foreach (PropertyData prop in wmiClass.Properties)
{
Console.WriteLine("{0, -30} {1}", prop.Name, prop.Type);
count++;
if (count % 15 == 0)
{
Console.WriteLine("\nPress any key to continue ...\n");
Console.ReadKey();
}
}
Console.ReadKey();
}
}
Andy WebsterPosted Sep 10, 2008, 8:00 AM
Thanks Alan, that is exactly what I was after. I just could not figure out the select statement to get the meta data so thankyou for preserving my sanity.
Having got the class name any idea how I can enumerate the properties for that class?
AlanPosted Sep 9, 2008, 5:09 PM
A bit more verbose than the VB Script but try this:
using System;
using System.Management;
class Program
{
static void Main()
{
ManagementScope scope = new ManagementScope("root\\cimv2");
WqlObjectQuery query = new WqlObjectQuery("select * from meta_class");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, null);
Console.Clear();
int count = 0;
foreach (ManagementClass wmiClass in searcher.Get())
{
Console.WriteLine(wmiClass["__CLASS"].ToString());
count++;
if (count % 20 == 0)
{
Console.WriteLine("\nPress any key to continue ...\n");
Console.ReadKey();
}
}
}
}