My Technical Notes

Wednesday, 12 July 2017

PowerShell `Out-GridView` Example for a DataTable

Given some sample C# code:


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp6
{
    public class XXClass
    {
        public static System.Data.DataTable CreateSampleDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Forename", typeof(string));
            dt.Columns.Add("Surname", typeof(string));

            {
                var row = dt.NewRow();
                row["ID"] = 1;
                row["Forename"] = "Tahir";
                row["Surname"] = "Hassan";
                dt.Rows.Add(row);
            }

            {
                var row = dt.NewRow();
                row["ID"] = 2;
                row["Forename"] = "Steven";
                row["Surname"] = "Gerrard";
                dt.Rows.Add(row);
            }

            {
                var row = dt.NewRow();
                row["ID"] = 3;
                row["Forename"] = "Luis";
                row["Surname"] = "Suarez";
                dt.Rows.Add(row);
            }

            return dt;
        }
    }
}

Setting `$code` to this text, you can run the following code to add this type:


Add-Type -TypeDefinition $code -ReferencedAssemblies System.Data, System.Xml

And you can use `Out-GridView` to view the output of the above class's method:


[ConsoleApp6.XXClass]::CreateSampleDt() | Out-GridView

No comments: