如何使用 C# Powershell 将 PSObject 转换为流输出或 DataTable System.Management.Automation

How to to Convert PSObject to Stream output or DataTable using C# Powershell System.Management.Automation

我需要以与 PowerShell 相同的方式将 PowerShell PSObject 转换为流式传输。 PowerShell 还以通用方式提供标准流的输出。

例如$PSVersionTable 仅输出 2 列(名称、值)而不是整个哈希表。 因此,我希望每个 PSObject 都以与 PowerShell 在后台执行的方式相同的标准方式进行处理。此外,我想将其转换为 DataTable。 我知道,还有其他链接说明了这个问题,但它们是对 PSObject 的所有属性进行操作的。 PowerShell 以某种方式开箱即用。

我需要将 PSObject 转换为其他类型吗?

例子

PowerShell 脚本输出 $PSVersionTable

PSVersion      5.1.17134.228
PSEdition      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}

$hostGet-Host 输出为

Get-WebApplication 输出

Name             Application pool   Protocols    Physical Path                                                                                                                                                                                                                 
----             ----------------   ---------    -------------                                                                                                                                                                                                                 
IisHostedServer  DefaultAppPool     http        C:\TestDirectory\Src\IisHostedServer  

Get-ChildItem -Path "C:\TestDirectory\TestSubDir\Studio":

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       29.06.2018     11:54                TestFileDir
d-----       24.07.2018     16:37                TestSites
-a----       13.08.2018     11:53            343 TestXml.xml

同样可以有其他参考或自定义类型。

我想在 C# 中以相同的方式获取这些输出,并且需要将它们显示为字符串或数据表。是否有从 PSObject 到流的任何转换或以完全通用的方式在输出上方 returns 的东西?

当我在 C# 中处理以下方法时:

var outputCollection = new PSDataCollection<PSObject>();

outputCollection.DataAdded += OnOutputDataAdded;
powerShell.Invoke(null, outputCollection);

private void OnOutputDataAdded(object sender, DataAddedEventArgs e)
{
    var records = (PSDataCollection<PSObject>) sender;
    var data = records[e.Index];
    var outputTable = ConverToLogableDataStream(data);
}
private void ConverToLogableDataStream(PSObject)
{
    ...
    ...
}

这个问题已经很老了,但请看一下 ConvertTo-Json 并将其转换为您选择的数据 table 或 class(为我工作)

例如。 电源外壳: 获取主机 | ConvertTo-Json

C#: JsonConvert.DeserializeObject< 列表 < class 名称 >> (PSObject)