【发布时间】:2015-07-29 16:33:48
【问题描述】:
如何在 C# 中解析 powerShell 控制台的输出?
PowerShell 控制台输出:
Name : 0F06B9DF-9FC5-4AF7-AF92-890AAD415000
ElementName : Virtual Machine 1
Name : 2B501DD8-46F5-45FE-ACCE-62030720A000
ElementName : Virtual Machine 2
在我的 C# 代码中逐行读取输出。我搜索将输出转换为
的最佳方法List<Dictionary<string, string>>
我试过了
bool dataset = false;
Dictionary<string, string> data = new Dictionary<string, string>();
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
// The line of Output
string line = proc.StandardOutput.ReadLine();
// If line is not empty save data in dictionary
if(line.Length != 0)
{
dataset = true;
string[] vals = line.Split(':');
data.Add(vals[0], vals[1]);
}
// Else, save dictionary in list and reinit dictionary
else
{
// Next object
if (dataset)
{
arr.Add(data);
dataset = false;
data = new Dictionary<string, string>();
}
}
}
【问题讨论】:
-
您可能希望显示用于生成该输出的命令。
-
为什么你需要一个字典列表,而只有一个字符串字典就足够了?
-
在我的情况下如何使用字符串字典? PS:我添加了我使用的代码。
-
您观察到的问题是什么?在什么情况下它不起作用?
-
它可以工作,但我正在寻找完成这项任务的最佳方式。
标签: c# parsing powershell output