Hey Y’all,
In my continuing quest to learn powershell I’ve come across a problem I can’t seem to get past.
The following code shows a dialog box of available drive letters. It works fine except in one condition.
If the user selects a drive then presses the cancel button the function still returns the selected drive.
I’ve tried and tried but can’t come up with a solution to tell which button was pressed. If I get a return value from the show form command it shows “cancel” for either button! :angry:
Function DriveList() { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") $Pushed = "" $drives = Get-PSDrive -PSProvider FileSystem $objForm = New-Object System.Windows.Forms.Form $objForm.Text = "Drive Selection" $objForm.Size = New-Object System.Drawing.Size(300,200) $objForm.StartPosition = "CenterScreen" $objForm.KeyPreview = $True $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") {$ExtDrive=$objListBox.SelectedItem;$objForm.hide()}}) $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") {$objForm.hide()}}) $OKButton = New-Object System.Windows.Forms.Button $OKButton.Location = New-Object System.Drawing.Size(10,120) $OKButton.Size = New-Object System.Drawing.Size(75,23) $OKButton.Text = "OK" $OKButton.Add_Click({$objForm.hide()}) $CancelButton = New-Object System.Windows.Forms.Button $CancelButton.Location = New-Object System.Drawing.Size(95,120) $CancelButton.Size = New-Object System.Drawing.Size(75,23) $CancelButton.Text = "Cancel" $CancelButton.Add_Click({$objForm.hide()}) $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 drive:" $objListBox = New-Object System.Windows.Forms.ListBox $objListBox.Location = New-Object System.Drawing.Size(10,40) $objListBox.Size = New-Object System.Drawing.Size(160,20) $objListBox.Height = 80 for( $curDrive = 0; $curdrive -lt $drives.Count; $curDrive++) { [void] $objListBox.Items.Add($drives[$curDrive].Name) } $drives = Get-PSDrive -PSProvider FileSystem $objForm.Controls.AddRange(@($OKButton,$CancelButton,$objLabel,$objListBox)) $objForm.Topmost = $True [void] $objForm.ShowDialog() $ExtDrive = $objlistbox.SelectedItem $ExtDrive #Return selected drive $objForm.dispose() } # End Function DriveList # Test code to call function: $ExtDrive = DriveList #Call Function # $ExtDrive += ":" #Note: This line NOT needed if only letter is required write-host "The selected drive is: $ExtDrive"
It’s probably simple but I sure can’t figure it out. :cheers: