PSobject输出到控制台

时间:2019-03-15 07:57:49

标签: c# .net powershell output

我是.net的新手。在将powershell命令输出到控制台(在c#中调用)时遇到问题。

代码:

    PowerShell powershellCommand = PowerShell.Create();
    powershellCommand.AddScript("get-process");
    Collection<PSObject> results = powershellCommand.Invoke();
    foreach (PSObject result in results)
    {
        Console.WriteLine(results);
    }
    Console.Read();

输出: System.Collections.ObjectModel.Collection`1 [System.Management.Automation.PSObject]

1 个答案:

答案 0 :(得分:0)

您正在遍历集合,但不是编写当前项目,而是整个集合。您必须输入以下内容:

PowerShell powershellCommand = PowerShell.Create();
powershellCommand.AddScript("get-process");
Collection<PSObject> results = powershellCommand.Invoke();
foreach (PSObject result in results)
{
    Console.WriteLine(result); //<-- result NOT results
}
Console.Read();
相关问题