How to add items to a listbox in Powershell?

Viewed 43

I have the following listbox and would like to add drivers and their versions into it. As of now, nothing is being added and I get a "Cannot find an overload for "Add" and the argument count: "1"" error.


#Driver List

$ListBox1 = New-Object System.Windows.Forms.ListView

$ListBox1.Location  = New-Object System.Drawing.Point(150,180)

$ListBox1.AutoSize = $true

$ListBox1.Scrollable = $true

$ListBox1.Text = Get-WmiObject Win32_PnPSignedDriver| select DeviceName, Manufacturer, DriverVersion | ForEach-Object {[void] $ListBox1.Items.Add($_)} 

$main_form.Controls.Add($ListBox1)


    }
)



1 Answers

Very rough working example below.

Iterate through the drivers, adding one at a time:

# main form
$main_form = New-Object System.Windows.Forms.Form
$main_form.Text = "Test"
$main_form.Size = '830,445'
$main_form.StartPosition = 'CenterScreen'

# Add Listview    
$ListBox1 = New-Object System.Windows.Forms.ListView
$ListBox1.Location  = '20,20'
$ListBox1.Size = '780,380'
$ListBox1.Scrollable = $true
$listBox1.View='Details'
# Add the columns you want to the listbox
$ListBox1.Columns.Add('DeviceName',120) | Out-Null
$ListBox1.Columns.Add('Manufacturer',120) | Out-Null
$ListBox1.Columns.Add('Version',120) | Out-Null
   
$main_form.Controls.Add($ListBox1)

# Anything in this section will be performed after form is visible rather than before
$main_form.add_Shown({ 

Get-WmiObject Win32_PnPSignedDriver| ForEach-Object { 
# Make sure there's a devicename present
    If ($_.DeviceName) {
#Entry first column is devicename
        $Entry = New-Object System.Windows.Forms.ListViewItem($_.DeviceName)
# Try next field
        Try {
            $Entry.SubItems.Add($_.Manufacturer) | Out-Null
        }
        Catch {
# Put in placeholder if field is empty
            $Entry.SubItems.Add("-")
        }
        Try {
# Try next field
            $Entry.SubItems.Add($_.DriverVersion) | Out-Null
        }
        Catch {
# Put in placeholder if field is empty
            $Entry.SubItems.Add("-")
        }
# Add the device entry to the listview
        $listBox1.Items.Add($Entry)
    }
}
    
# Resize columns to content
$ListBox1.AutoResizeColumns(1) 
})
# Show form
$main_form.ShowDialog() | Out-Null
Related