Search code examples
powershellvariablescomboboxbuttonclick

ComboBox selection to variable


I'm writing a GUI script to mapp network shares as drives. I have created (with the help of other SO users) a working combobox listing unused drive lettes. What I'd like to do now is to capture, after button click, selected combobox item into a variable to be used in another, not yet implemented part of script. So far I've managed to get the script to 'write-host' the selected item. Please help

$form = New-Object System.Windows.Forms.Form
$form.Text = 'Test' 
$form.Size = New-Object System.Drawing.Size(280,400) 
$form.StartPosition = 'Manual'
$form.Location      = '10,10'
$form.Topmost = $true  

$button = New-Object System.Windows.Forms.Button
$button.Size = New-Object System.Drawing.Size(50,20)
$button.Location = New-Object System.Drawing.Size(20,20)
$button.Text = "Literki"
$button.Add_Click($button_click)

$button2 = New-Object System.Windows.Forms.Button
$button2.Size = New-Object System.Drawing.Size(50,20)
$button2.Location = New-Object System.Drawing.Size(20,80)
$button2.Text = "Text"
$button2.Add_Click($button_click2)

$comboBox1 = New-Object System.Windows.Forms.ComboBox 
$comboBox1.Location = New-Object System.Drawing.Point(80, 55) 
$comboBox1.Size = New-Object System.Drawing.Size(98, 10) 
$comboBox1.Add_SelectedIndexChanged(
    { $A =$ComboBox1.Text
    write-host $A}
    )
$ComboBox1.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList;


$AllLetters = 67..90 | ForEach-Object {[char]$_ + ":"}
$UsedLetters = Get-WmiObject Win32_LogicalDisk | Select -Expand DeviceID
$FreeLetters = $AllLetters | Where-Object {$UsedLetters -notcontains $_}
ForEach ($Letter in $FreeLetters) { $comboBox1.Items.Add($Letter) }



$button_click = {Write-Host $FreeLetters} 

$button_click2 = {write-host $A}

$form.Controls.AddRange(@($button, $combobox1,$button2))
$form.ShowDialog()

Solution

  • You need to scope the variable so that it's available outside of the function.

    $comboBox1.Add_SelectedIndexChanged({
        $Script:A =$ComboBox1.Text
    })
    $button_click2 = {Write-Host $Script:A}
    

    See https://www.varonis.com/blog/powershell-variable-scope/ for more details