5

I've written a Powershell script that reads a CSV file and returns a predetermined collection from the data. Below is a sample output of said script.

Count     Name
------   ------
  12      Rubies
   3      Pearls
  20      Emeralds

I am able to obtain the results in C# by storing it in a PSObject like so:

var shell = PowerShell.Create();
shell.Commands.AddScript("C:\\Scripts\\Powershell\\Get-MyData.ps1");
Collection<PSObject> results = shell.Invoke();

Now when I'm expecting a single object, I am able to obtain each value and assign them to variables like this:

foreach (PSObject psObject in results)
{
   localVariable = Convert.ToString(psObject.Properties["Name"].Value);
}

However, I am having trouble converting this solution to a dynamic one. That is to say, the number of rows is expected to vary. So I've implemented this before when the source is a SQL database using a solution similar to the one posted here so I've assumed that datatables should be the way to go but I cannot get it to work in this scenario. Any ideas or suggestions? Thanks!

Note: The Powershell script component here is compulsory as it includes other mechanisms to formulate the output so while I could just read from the CSV file using C#, this is simply not an option.

4

3 回答 3

1

既然您已经在使用 powershell 来读取 csv 文件,为什么不继续呢?

在开始用 C# 管理它之前,您可以调用 powershell 命令/脚本来迭代 *.ps1 文件的结果。

在 c# 中调用脚本非常容易,您不必将脚本创建为文件。您可以直接发送脚本文本并调用它。

也许您甚至可以将两者结合起来,类似于:

var shell = PowerShell.Create();
shell.Commands.AddScript("C:\\Scripts\\Powershell\\Get-MyData.ps1 | foreach {do-something $_}");
Collection<PSObject> results = shell.Invoke();

请注意,我在您的脚本结果返回后添加了一个管道。请记住,“AddScript”非常类似于向 powershell.exe 发送一堆文本。我之前已经将整个脚本文件从嵌入式资源推送到此方法。

于 2017-01-22T01:49:17.927 回答
1

Use Linq:

IEnumerable<dynamic> dynamicResults = from item in results                                     
                                      select new { Name = item.Name, Count = item.Count };

Then set the myDataGrid.ItemsSource = dynamicResults;

于 2017-01-22T02:02:43.213 回答
1

我从您的问题中了解到的是,您希望拥有 DataTable 以进行进一步的数据处理,并且您希望在各自的集合中使用它。

你可以这样进行:

DataTable dt=new DataTable();
dt.Colums.Add("Count");
dt.Colums.Add("Name");
foreach (PSObject psObject in results)
{
   foreach(PSPropertyInfo prop in psObject.Properties)
   {
     var count=prop.Name; 
     var name=prop.Value;
     //In other words generate output as you desire.
     dt.Rows.Add(count,name);
   }
}

希望对你有帮助。

存在文档:Doc 1Doc 2

于 2017-01-17T23:22:58.417 回答