首页 > 解决方案 > PSobject 输出到控制台

问题描述

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

代码:

    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]

标签: c#.netpowershelloutput

解决方案


您正在迭代您的集合,但您不是在编写当前项目,而是整个集合。你必须写项目:

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();

推荐阅读