在powershell中将网络打印机设置为默认打印机

z0qdvdin  于 2023-10-18  发布在  Shell
关注(0)|答案(2)|浏览(278)

我正在编写一个脚本,使用户更容易添加网络打印机。使用“listBox”,它显示了我的打印服务器中所有已配置的打印机,并通过按下我的“添加打印机”按钮,它将自动添加。
现在我想做第二个按钮,它将从列表中选择的设备设置为默认打印机。
我只知道SetDefaultPrinter命令,但我不认为这是正确的。
下面是我的代码:

  1. #window
  2. $window = New-Object System.Windows.Forms.Form
  3. $window.Text = 'Select a Printer'
  4. $window.Size = New-Object System.Drawing.Size(500, 400)
  5. $window.StartPosition = 'CenterScreen'
  6. #okButton
  7. $okButton = New-Object System.Windows.Forms.Button
  8. $okButton.Location = New-Object System.Drawing.Point(340,130)
  9. $okButton.Size = New-Object System.Drawing.Size(96,48)
  10. $okButton.Text = 'Drucker installieren'
  11. $okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
  12. $window.AcceptButton = $okButton
  13. #favoriteButton
  14. $favoriteButton = New-Object System.Windows.Forms.Button
  15. $favoriteButton.Location = New-Object System.Drawing.Point(340,240)
  16. $favoriteButton.Size = New-Object System.Drawing.Size(96,48)
  17. $favoriteButton.Text = 'Als Standarddrucker festlegen'
  18. $favoriteButton_Click{
  19. }
  20. #Label
  21. $label = New-Object System.Windows.Forms.Label
  22. $label.Location = New-Object System.Drawing.Point(10,20)
  23. $label.Size = New-Object System.Drawing.Size(280,20)
  24. $label.Text = 'Please select a printer'
  25. #ListBox
  26. $listBox = New-Object System.Windows.Forms.ListBox
  27. $listBox.Location = New-Object System.Drawing.Point(10,60)
  28. $listBox.Size = New-Object System.Drawing.Size(260,20)
  29. $listBox.Height= 280
  30. Get-Printer -ComputerName srvpr01 | Sort-Object | ForEach-Object { $listBox.Items.Add($_.Name) }
  31. $window.TopMost = $true
  32. $window.Controls.Add($listBox)
  33. $window.controls.Add($label)
  34. $window.Controls.Add($favoriteButton)
  35. $window.Controls.Add($okButton)
  36. $result = $window.ShowDialog()
  37. if ($result -eq [System.Windows.Forms.DialogResult]::OK){
  38. $x = $listBox.SelectedItem
  39. Add-Printer -ConnectionName \\srvpr01\$x
  40. }

我感谢任何类型的帮助和反馈!

cuxqih21

cuxqih211#

首先使用以下命令添加打印机:

  1. ([wmiclass]"Win32_Printer").AddPrinterConnection("$($ServerShareName)")

然后使用以下命令将其设为默认值:

  1. (Get-WmiObject -class win32_printer -Filter "ShareName='$ServerShareName'").SetDefaultPrinter()
j5fpnvbx

j5fpnvbx2#

这里有两种方法,使用wmi或com对象。它必须以每个用户的身份运行。https://learn.microsoft.com/en-us/powershell/scripting/samples/working-with-printers?view=powershell-7#setting-a-default-printer

相关问题