C# Powershell results RRS feed

  • Question

  • Looking for help on adding a collection from powershell into a datagrid. I have something like this so far..

    PowerShell ps = PowerShell.Create();
    ps.Runspace = RunspaceFactory.CreateRunspace();
    ps.AddScript("Get-Process | FT Name, ProcessName");
    var results = ps.Invoke();
    dataGridView1.DataSource = results;

    My datagrid has 2 columns, ID & ProcessName. Trying to add the results from the powershell command to the datagrid in that same fashion.

    Tuesday, February 27, 2018 8:47 PM

All replies

  • Please identify what UI technology you are using so we can move this question to the appropriate forums.

    Michael Taylor

    Tuesday, February 27, 2018 9:02 PM
  • Hello Sinteck,

    You can't pass collection of PSObject to datasource directly. You need to retrieve relating data and regroup it as right format that datagridview recognized. The below way is good choice for you.

                string temp = "|out-String";
                PowerShell ps = PowerShell.Create();
                ps.Runspace = RunspaceFactory.CreateRunspace();
                ps.AddScript("Get-Process| FT Name, ProcessName" + temp);
                var results = ps.Invoke();
                string[] lines = null;
                var result = results[0];
                //parse the output
                var  output = result.ToString().Trim(new char[] { '\r', '\n' });
                lines= output.Split(new string[] {Environment.NewLine},StringSplitOptions.None);
                DataTable dt = new DataTable();
                //add columns to datatable
                var columns = Regex.Split(lines[0], "\\s{2,}", RegexOptions.IgnoreCase).Where(x=>x!="").ToArray();
                foreach (var column in columns)
                dt.Columns.Add(new DataColumn(column));
                //add rows to datatable
                for (int i = 1; i < lines.Length; i++) {
                    var rows = Regex.Split(lines[i], "\\s{2,}", RegexOptions.IgnoreCase).Where(x=>x!="").ToArray();
                dataGridView1.DataSource = dt;

    The result.

    Best regards,

    Neil Hu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Wednesday, February 28, 2018 7:06 AM