PowerShell Property Grid Editor
Posted: July 8, 2012 Filed under: PowerShell, Windows Forms | Tags: PowerShell, WinForms Leave a commentExample of how to open a Windows form with a property grid from PowerShell to edit an arbitrary objects properties. May be useful for editing configuration files that you have generated classes for and can serialize.
New-Module -ScriptBlock {
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$form = New-Object System.Windows.Forms.Form
$grid = New-Object System.Windows.Forms.PropertyGrid
$grid.Dock = [System.Windows.Forms.DockStyle]::Fill
$button = New-Object System.Windows.Forms.Button
$button.Text = "OK"
$button.Dock = [System.Windows.Forms.DockStyle]::Bottom
$form.Controls.Add($button)
$form.Controls.Add($grid)
# Item to return, not null for OK
$item = $null
$button.add_Click(
{
# Set the return item
$item = $grid.SelectedObject
$form.Close()
}
)
function Edit-Object($obj) {
# Item to return, null for Cancel
$item = $null
$grid.SelectedObject = $obj
$form.ShowDialog() | Out-Null
return $item
}
Export-ModuleMember -Function Edit-Object
} | Out-Null
cls
$obj = New-Object System.Windows.Forms.Button
$ret = (Edit-Object $obj)
if ($ret) {
$ret
}