Search code examples
powershelllistboxadditionprintersnetwork-printers

List Every Network Printer With ListBox Powershell


I'm new to Powershell and I would like to write a script to make it easier for end users to add a network printer to their system.

I want to list all the network printer in the listbox, but instead of listing all printer names, I get this: System.Object

Here's my code

#window
$window = New-Object System.Windows.Forms.Form
$window.Text = 'Select a Printer'
$window.Size = New-Object System.Drawing.Size(500, 400)
$window.StartPosition = 'CenterScreen'

#Button
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(340,130)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$window.AcceptButton = $okButton

 $cancelButton = New-Object System.Windows.Forms.Button
 $cancelButton.Location = New-Object System.Drawing.Point(340,240)
 $cancelButton.Size = New-Object System.Drawing.Size(75,23)
 $cancelButton.Text = 'Cancel'
 $cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
 $window.CancelButton = $cancelButton

 $label = New-Object System.Windows.Forms.Label
 $label.Location = New-Object System.Drawing.Point(10,20)
 $label.Size = New-Object System.Drawing.Size(280,20)
 $label.Text = 'Please select a printer'

 $listBox = New-Object System.Windows.Forms.ListBox
 $listBox.Location = New-Object System.Drawing.Point(10,60)
 $listBox.Size = New-Object System.Drawing.Size(260,20)
 $listBox.Height= 280


 $listBox.Items.Add((Get-Printer -ComputerName srvpr01| select $_.Name))


 $window.Controls.Add($listBox)
 $window.controls.Add($label)
 $window.Controls.Add($cancelButton)
 $window.Controls.Add($okButton)
 $result = $window.ShowDialog()

 if ($result -eq [System.Windows.Forms.DialogResult]::OK)
  {
     $x = $listBox.SelectedItem
     $x
  }

You know any way I can list the printer names instead of this Object? I appreciate every type of help and feedback!


Solution

  • You need to use a loop to add the items to the listbox.

    Change this line

    $listBox.Items.Add((Get-Printer -ComputerName srvpr01| select $_.Name))
    

    to this:

    Get-Printer -ComputerName srvpr01 | ForEach-Object { $listBox.Items.Add($_.Name) }