如何通过Powershell彻底删除设备和打印机中的本地打印机?
Powershell彻底移除本地打印机(清除「设备和打印机」残留方案)
问题原因
现有Remove-Printer命令仅清理打印服务子系统内的配置记录,「设备和打印机」界面的条目属于Windows即插即用(PNP)设备管理范畴,未同步删除PNP设备实例就会残留「驱动程序不可用」的错误条目,导致后续开机脚本执行失败。
优化后关机脚本
# 定义目标打印机名称 $printerName = "Reports" # 停止打印后台服务,避免资源锁定 Stop-Service Spooler -Force # 获取打印机对象,避免多余的CSV转换操作 $printer = Get-Printer -Name $printerName -ErrorAction SilentlyContinue if ($printer) { $driverName = $printer.DriverName $portName = $printer.PortName # 移除打印机 Remove-Printer -Name $printerName -Confirm:$false -ErrorAction SilentlyContinue # 移除对应端口 if ($portName) { Remove-PrinterPort -Name $portName -Confirm:$false -ErrorAction SilentlyContinue } # 清理PNP设备层的打印机残留 $pnpPrinter = Get-PnpDevice -Class Printer -FriendlyName $printerName -ErrorAction SilentlyContinue if ($pnpPrinter) { Remove-PnpDevice -InstanceId $pnpPrinter.InstanceId -Confirm:$false -ErrorAction SilentlyContinue } # 可选:清理当前用户和本地机器注册表中的残留打印机项 Remove-Item -Path "HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Devices\$printerName" -Force -ErrorAction SilentlyContinue Remove-Item -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Print\Printers\$printerName" -Force -Recurse -ErrorAction SilentlyContinue } # 重启打印后台服务 Start-Service Spooler -ErrorAction SilentlyContinue
部署注意事项
- 脚本需要管理员权限执行,在OU组策略配置关机脚本时,需将脚本运行上下文设置为「计算机账户」,避免权限不足无法操作PNP设备和注册表
- 不需要保留原脚本中的打印机重命名操作,直接针对原打印机名称操作即可,减少异常概率
- 若你对接的打印机有特殊的PNP名称规则,可以调整
Get-PnpDevice的筛选参数适配
内容的提问来源于stack exchange,提问作者scotthannah
相关产品推荐
相关产品推荐

