首页 > 解决方案 > 在 C# 中模仿这个非常简单的 powershell 命令

问题描述

试图模仿Get-CimInstance CIM_ManagedSystemElementC# 中的命令

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"]);
}

可悲的是,这没有按预期工作,想得到一些帮助

谢谢

标签: c#wmicim

解决方案


我也无法让您的代码正常工作,但与此同时,如果您需要解决方法,您可以使用我根据一些在线文档编写的这个简单程序在 C# 中使用 PowerShell API。它会给你一个你正在寻找的输出。您应该可以访问 OutputCollection_DataAdded 中的所有属性,因此如果您需要的不仅仅是 Caption,您可以在此处获取它。此外,在执行结束时有一个 foreach() 循环,如果您需要对其执行某些操作,它将包含整个输出集合。执行速度非常慢,所以我不得不让它异步工作。

    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}");
            }
        }
    }

推荐阅读