Tuesday 1 December 2015

Powershell GUI Interface

I was required to add my first powershell GUI today. The following code allows for a drop down selection box so this is handy to let a user choose from a variety of options to allow the script to continue.

The main window coding can be re-used multiple times as most of the code is the window size and postion etc..

This selector example reads an input CSV file to display to the user to select. It display the Site column information within the text file.

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

$objForm = New-Object System.Windows.Forms.Form $objForm.Text = "DesktopConnect Build Script"
$objForm.Size = New-Object System.Drawing.Size(300,200) $objForm.StartPosition = "CenterScreen"
$objForm.opacity = 1.0

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {$global:XDSiteList=$objListBox.SelectedItem;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.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({$global:XDSiteList=$objListBox.SelectedItem;$objForm.
Close()})
$objForm.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({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

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

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

Import-csv "C:\Scripts\input.txt" | ForEach-Object {[void] $objListBox .Items.Add($_.Site)}

$objForm.Controls.Add($objListBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})

[void] $objForm.ShowDialog()

# This pipes the chosen action from the imported CSV file
$XDSiteList

No comments:

Post a Comment