在C#中使用PowerShell命令“ Get-LocalGroup”

时间:2019-05-22 12:04:25

标签: c# powershell

当我尝试在c#应用程序中使用PowerShell cmdlet“ Get-LocalGroup”时,它不会在控制台上打印出该cmdlet的任何输出。

我已经包含了Management.Automation NuGet。 构建过程可以顺利进行。 我还尝试在调试和发布模式下以管理员权限启动内置的.exe。

using System.Collections.ObjectModel;
using System.Management.Automation;

namespace RunPowershell
{
    class Program
    {
        static void Main(string[] args)
        { 
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript("Get-LocalGroup");

                Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

                // loop through each output object item
                foreach (PSObject outputItem in PSOutput)
                {
                    if (outputItem != null)
                    {
                            System.Console.WriteLine("-"+outputItem.BaseObject);
                    }
                }
                System.Console.WriteLine("Hit any key to exit.");
                System.Console.ReadKey();
            }
        }
    }
}

在调试窗口中看不到重大错误,但也没有“ Get-LocalGroup”的输出。

1 个答案:

答案 0 :(得分:0)

Get-LocalGroup缺少输出是由于项目的CPU目标。如果是x86Any CPU,则Get-localGroup将不起作用,因为它仅在x64主机中有效。如果打开x86 PowerShell控制台,则可以看到它的作用-它会抱怨没有这样的命令。您还可以在C#项目的PowerShellInstance.Streams.Error流中看到该错误。

固定目标之后,由于Powershell将结果存储在集合中而不是简单的属性中,因此您需要手动提取/格式化结果。看看我以前的答案,关于如何通过将结果转换为自定义对象来使自己的生活更轻松:

Dealing with CimObjects with PowerShell inside C#

相关问题