2

I'm trying to write a PowerShell script that will include a list box. To make sure I've got my head wrapped around the concepts needed, I've looked up a tutorial on TechNet and tried to duplicate the code provided.

http://technet.microsoft.com/en-us/library/ff730949.aspx

If I'm following the walkthrough and script properly, it appears that the script is intended to present a dialog box and then output the selected item to the CLI. I've duplicated the dialog box, but I can't get it to write the selection to the CLI. I even modified the last line to explicitly call Write-Output to show the value of $x.

Everything about this script appears to work as intended, except for actually writing out any value for $x. Since echo "$x" is perhaps the simplest line in all that code, I can only presume the problem is actually with getting data written to $x instead.

Below is cut-and-paste from my PowerShell ISE window, which in turn was cut-and-paste from the aforementioned TechNet article:

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

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

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$x=$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({$x=$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 computer:"
$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

[void] $objListBox.Items.Add("atl-dc-001")
[void] $objListBox.Items.Add("atl-dc-002")
[void] $objListBox.Items.Add("atl-dc-003")
[void] $objListBox.Items.Add("atl-dc-004")
[void] $objListBox.Items.Add("atl-dc-005")
[void] $objListBox.Items.Add("atl-dc-006")
[void] $objListBox.Items.Add("atl-dc-007")

$objForm.Controls.Add($objListBox) 

$objForm.Topmost = $True

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

echo "$x"

When the above didn't work as expected, I decided to go step-by-step with the tutorial and re-write the script myself. I modified it a bit to better suit my organizational preferences and to add annotations along the way. However, now even the dialog itself is broken.

# Load Windows Forms & Drawing classes.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

# Create base form.
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Select a Computer"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"

# Configure keyboard intercepts for ESC & ENTER.
$objForm.KeyPreview = $true
$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Enter")
    {
        $x = $objListBox.SelectedItem
        $objForm.Close()
    }
})
$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Escape")
    {
        $objForm.Close()
    }
})

# Create OK button.
$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 = $objListBox.SelectedItem
    $objForm.Close()
})
$objForm.Controls.Add($OKButton)

# Create Cancel button.
$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)

# Add form prompt text.
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Text = "Please select a computer:"
$objForm.Controls.Add($objLabel)

# Add list box.
$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

# Populate list.
[void] $objListBox.Items.Add("Option1")
[void] $objListBox.Items.Add("Option2")
[void] $objListBox.Items.Add("Option3")
[void] $objListBox.Items.Add("Option4")
[void] $objListBox.Items.Add("Option5")
[void] $objListBox.Items.Add("Option6")
[void] $objListBox.Items.Add("Option7")

# Force list box to display on top of other windows.
$objForm.TopMost = $true

# Display list box.
$objForm.Add_Shown({
    $objForm.Activate()
})
[void] $objForm.ShowDialog()

# Show result.
$x

The second code block results in this:

Broken list box

What am I doing wrong, here?

Note: I'm running PowerShell 3.0 on Windows 7

2 Answers 2

5

An easy way to get the functionality of a list box is to use Out-GridView. For example:

'one','two','three','four' | Out-GridView -OutputMode Single

The user can select an item, and it will be returned in the pipeline.

You can also use -OutputMode Multiple for multi-selection.

Another example:

get-process | Out-GridView -OutputMode Multiple

enter image description here

This returns the selected object:

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    396      24     5008       8964   113     8,88   3156 AuthManSvr
1

Modify the OK button click handler to this:

$OKButton.Add_Click({$global:x=$objListBox.SelectedItem;$objForm.Close()})

Note the use of the global: scope specifier for the $x variable. PowerShell uses dynamic scoping and employs a "copy-on-write" approach to variables. That is, assuming $x is defined in the global scope, modifying $x in a function would only modify a local copy of the variable. If your intent is to modify the global value of $x you must use the global specifier e.g. $global:x = ....

7
  • This sounds like it might reach outside the scope of the script. How can I use $x outside of that function while keeping it contained within the script? Also, what did I do that broke the dialog display in the second script?
    – Iszi
    Aug 13, 2013 at 2:19
  • Ok, I think I figured out the first part of my comment-question. I changed $x to $script:x and that seems to have worked. Still, what's wrong in my second script?
    – Iszi
    Aug 13, 2013 at 3:08
  • Nevermind. Found it. I was missing $objForm.Controls.Add($objListBox).
    – Iszi
    Aug 13, 2013 at 3:26
  • Last question: Since this script originated from a TechNet article, and there are similar scripts in the same series which define $x in a similar fashion, it would seem that this should have worked. Has something changed in PowerShell (e.g.: From 1.0 to 2.0, or to 3.0) that invalidated the script as it was originally written?
    – Iszi
    Aug 13, 2013 at 3:36
  • 1
    The original code worked in 1.0 and 2.0. It breaks starting with 3.0. If you look at the WMF 3.0 Release Notes there is a documented breaking change called "Script blocks executed as delegates run in their own scope" that describes the change.
    – Keith Hill
    Aug 13, 2013 at 5:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.