powershelladditionprintersnetwork-printers

Set a network printer as the default printer in powershell


I'm writing a script that makes it easier for users to add a network printer. With the "listBox", it shows all the configured printers in my printserver and by pressing my "add printer"- Button, it'll automatically be added.

Now I want to do a second button, which sets a chosen device from the list as a default printer.

I only know the SetDefaultPrinter command, but I don't think that's the right one.

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'

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

#favoriteButton
$favoriteButton = New-Object System.Windows.Forms.Button
$favoriteButton.Location = New-Object System.Drawing.Point(340,240)
$favoriteButton.Size = New-Object System.Drawing.Size(96,48)
$favoriteButton.Text = 'Als Standarddrucker festlegen'
$favoriteButton_Click{

}

#Label
$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
$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

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

$window.TopMost = $true

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

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

I appreciate any type of help and feedback!


Solution

  • There's two ways documented here, using wmi or a com object. It would have to be run as each user. https://learn.microsoft.com/en-us/powershell/scripting/samples/working-with-printers?view=powershell-7#setting-a-default-printer