Returns PSObject Powershell as DataTable in C #

I wrote a Powershell script that reads a CSV file and returns the given collection from the data. The following is sample script output.

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

I can get the results in C # by saving it in PSObject like this:

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

Now, when I expect one object, I can get each value and assign them to the following variables:

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

However, I had problems converting this solution to dynamic. That is, it is expected that the number of rows will change. Therefore, I implemented this earlier when the source code is an SQL database using a solution similar to the one posted here , so I assumed that the data should be capable but I cannot get it to work in this scenario. Any ideas or suggestions? Thanks!

Note. The Powershell script component is required here, as it includes other mechanisms for formulating the output, so although I could just read from the CSV file using C #, this is simply not an option.

+5
source share
3 answers

What I understood from your question is that you want to have a DataTable for further data processing and want to use it in your respective collection.

You can do the following:

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

Hope it will be helpful for you.

Documents Available: Doc 1 and Doc 2

+1
source

since you are already using powershell to read the csv file, why not continue?

You can call the powershell / script command to repeat the results of your * .ps1 file before you start managing it in C #.

It is very easy to call a script in C #, and you do not need to create a script as a file. You can simply send the script text directly and call it.

maybe you can even combine 2 similar to:

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

Please note that I added the channel after receiving the script results. Remember that "AddScript" is very similar to sending a bunch of text to the powershell.exe file. I have so far pushed whole script files from embedded resources into this method.

+1
source

Use Linq:

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

Then set myDataGrid.ItemsSource = dynamicResults;

+1
source

Source: https://habr.com/ru/post/1261753/


All Articles