PowerShell Simple GUI

GOAL: Execute a simple GUI PowerShell script that lets you select an item from a list.

PowerShell doesn't just do scripting in the classic sense; since it can access Windows GUI elements, you can incorporate GUIs in your code. Here's an example (download):

# present a list, report back which item was selected

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

$Form = New-Object System.Windows.Forms.Form 
$Form.Text = "Select a Flavor"
$Form.Size = New-Object System.Drawing.Size(300,200) 
$Form.StartPosition = "CenterScreen"

$Form.KeyPreview = $True
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$x=$ListBox.SelectedItem;$Form.Close()}})
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$Form.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$ListBox.SelectedItem;$Form.Close()})
$Form.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$Form.Close()})
$Form.Controls.Add($CancelButton)

$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Size(10,20) 
$Label.Size = New-Object System.Drawing.Size(280,20) 
$Label.Text = "Please select a flavor:"
$Form.Controls.Add($objLabel) 

$ListBox = New-Object System.Windows.Forms.ListBox 
$ListBox.Location = New-Object System.Drawing.Size(10,40) 
$ListBox.Size = New-Object System.Drawing.Size(260,20) 
$ListBox.Height = 80

[void] $ListBox.Items.Add("Vanilla")
[void] $ListBox.Items.Add("Chocolate")
[void] $ListBox.Items.Add("Strawberry")
[void] $ListBox.Items.Add("Peppermint")
[void] $ListBox.Items.Add("Rocky Road")
[void] $ListBox.Items.Add("Butterscotch")
[void] $ListBox.Items.Add("Pistachio")

$Form.Controls.Add($ListBox) 

$Form.Topmost = $True

$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()

$x

Summary

It is possible (albeit somewhat painful) to construct GUIs in PowerShell and have them interact with your script logic.