gpt4 book ai didi

c# - 在 C# 中解析 PowerShell 输出

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:38 24 4
gpt4 key购买 nike

如何在 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>();
}
}
}

最佳答案

如果进程很快完成并且没有提供大量输出,那么最好等待它退出,然后立即读取所有标准输出流。

proc.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds);

var ret = new List<Dictionary<string, string>>();

// first split on double newline to separate VMs
string[] vms = proc.StandardOutput.ReadToEnd()
.Split(new[] { string.Format("{0}{0}", Environment.NewLine) }, StringSplitOptions.RemoveEmptyEntries);

foreach (var vm in vms)
{
// then split on newline, to get each line in separate string
var lines = vm.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

// finally, split each line on ':' to fill in dictionary, then add it to list
ret.Add(lines.Select(line => line.Split(':')).ToDictionary(a => a[0].Trim(), a => a[1].Trim()));
}

您可能还想将其包装在 try...catch 中,以防过程输出不是您期望的格式。

关于c# - 在 C# 中解析 PowerShell 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com