简体   繁体   中英

Mimic this very simple powershell command in C#

Trying to mimic the command Get-CimInstance CIM_ManagedSystemElement in C#

string NamespacePath = "\\\\.\\Root\\CIMv2";
string ClassName = "CIM_ManagedSystemElement";

//Create ManagementClass
ManagementClass oClass = new ManagementClass(NamespacePath + ":" + ClassName);

//Get all instances of the class and enumerate them
foreach (ManagementObject oObject in oClass.GetInstances())
{
    //access a property of the Management object
    Console.WriteLine("Caption : {0}", oObject["Caption"]);
}

Sadly, that didnt work as expected, would like to get some help

Thanks

I also couldn't get your code to work, but in the meantime if you need a workaround you can use the PowerShell API from within C# using this simple program I wrote based on some online documentation. It will give you an output you're looking for. You should have access to all the properties in OutputCollection_DataAdded so if you need more than Caption you can grab it here. Also, at the end of the execution there is a foreach() loop that will contain the entire output collection if you need to do something with that. The execution is extremely slow so I had to make it async to work.

    static void Main(string[] args)
    {
        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddCommand("Get-CimInstance");
            ps.AddParameter("-ClassName", "CIM_ManagedSystemElement");

            var outputCollection = new PSDataCollection<PSObject>();
            outputCollection.DataAdded += OutputCollection_DataAdded;

            // invoke execution on the pipeline (collecting output)
            var async = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);

            // do something else until execution has completed.
            // this could be sleep/wait, or perhaps some other work
            while (async.IsCompleted == false)
            {
                Console.WriteLine("Waiting for pipeline to finish...");
                Thread.Sleep(1000);

                // might want to place a timeout here...
            }

            Console.WriteLine("Execution has stopped. The pipeline state: " + ps.InvocationStateInfo.State);

            // loop through each output object item
            foreach (PSObject outputItem in ps.EndInvoke(async))
            {
                // if null object was dumped to the pipeline during the script then a null
                // object may be present here. check for null to prevent potential NRE.
                if (outputItem != null)
                {
                    //TODO: do something with the output item 
                    // outputItem.BaseOBject
                }
            }

            Console.Read();
        }
    }

    private static void OutputCollection_DataAdded(object sender, DataAddedEventArgs e)
    {
        if (sender is PSDataCollection<PSObject>)
        {
            var output = (PSDataCollection<PSObject>)sender;

            // Handle the output item here
            var caption = output.Last().Properties["Caption"];
            if (caption != null)
            {
                Console.WriteLine($"Caption: {caption.Value}");
            }
        }
    }

You do this like this (you have to add System.Management namespace)

Because CIM_ManagedSystemElement is at the default WMI namespace( which is Root\\CIMV2 ) you don't have to specify it at ManagementObjectSearcher .

Also, be sure that you have the minimum supported client- Windows Vista

    string query = @"SELECT * FROM CIM_ManagedSystemElement";


    var moSearch = new ManagementObjectSearcher(query);
    var moCollection = moSearch.Get();

    foreach (ManagementObject mo in moCollection)
    {
        Console.WriteLine("Caption = " + mo["Caption"]);
    }

Furthermore i suggest you use an ORM to remove boilerplate code like ORMi or Kexla

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM