PowerShell and DataSets

These are all somewhat old libraries, but still properly supported and very stable.

PowerShell and WinForms

# Remember to run Set-ExecutionPolicy -Scope Process Unrestricted

Add-Type -assembly System.Windows.Forms

$grid = New-Object System.Windows.Forms.DataGridView
$grid.Dock = [System.Windows.Forms.DockStyle]::Fill

$form = New-Object System.Windows.Forms.Form
$form.Controls.Add($grid)
$form.Text = "DataSet"

$form.ShowDialog()

PowerShell and ADO.NET

# Remember to run Set-ExecutionPolicy -Scope Process Unrestricted
$ds = New-Object System.Data.DataSet

$dt = $ds.Tables.Add("Posts")
$dt.Columns.Add("Url", [System.Type]([System.String]))
$dt.Columns.Add("Title", [System.Type]([System.String]))
$dt.Columns.Add("Date", [System.Type]([System.DateTime]))

Simple DataSet operations

All together now, here is a simple script that will create a new data set if needed and load/save from a file.

You can use this to do a bit of structured data entry quickly and keep multiple tables in a file for example.

# Remember to run Set-ExecutionPolicy -Scope Process Unrestricted

Add-Type -assembly System.Windows.Forms

$grid = New-Object System.Windows.Forms.DataGridView
$grid.AutoGenerateColumns = $true
$grid.Dock = [System.Windows.Forms.DockStyle]::Fill

$ds = New-Object System.Data.DataSet
$fn = "C:\nobackup\foo.xml"
if ([System.IO.File]::Exists($fn)) {
  $_ = $ds.ReadXml($fn)
} else {
  $dt = $ds.Tables.Add("Posts")
  $_ = $dt.Columns.Add("Url", [System.Type]([System.String]))
  $_ = $dt.Columns.Add("Title", [System.Type]([System.String]))
  $_ = $dt.Columns.Add("Date", [System.Type]([System.DateTime]))
}

$grid.DataSource = $ds
$grid.DataMember = "Posts"

$form = New-Object System.Windows.Forms.Form
$form.Controls.Add($grid)
$form.Text = $fn

$form.ShowDialog()
$ds.WriteXml($fn, [System.Data.XmlWriteMode]::WriteSchema)

Happy editing!

See How to Create a GUI for PowerShell Scripts for more ideas! See DataSets, DataTables, and DataViews on how to create and edit DataSet objects along with tables, rows, views, relations, etc.

Tags:  powershellxml

Home