我编写了一个删除网络打印机的 powershell 脚本。它按照用户偏好设置中 GPP 部署的计划运行,在任何会话登录时运行。
这是脚本。它确实搜索具有网络主机地址的打印机,该地址与 var $port 相等,但没有 var $imprimante 的名称。脚本确实查找具有 TCP/IP 端口和 WSD 端口的打印机
get-date > C:\Temp\debug.txt
###Variables###
$imprimante = "001 - HP LaserJet Pro M400 color M451dn (Salle prof)"
$port = "10.26.57.21"
###End###
Write-Host "Start Standard TCP/IP Printer"
Get-WmiObject win32_tcpipprinterport | select name, hostaddress | %{
$printer = New-Object System.Object
$printer | Add-Member -type NoteProperty -Name Name -Value $_.name -PassThru | Add-Member -type NoteProperty -Name HostAddress -Value $_.HostAddress
if ($printer.hostaddress -like $port)
{
$name = $printer.name
$p = Get-WmiObject win32_Printer -Filter "PortName like '$name' and not (Name like '$imprimante')"
$count = $p | measure
if ($count.count -gt 0)
{
$pn = $p | Select property -ExpandProperty Name
Write-Host "The printer '$pn' is going to be removed."
$p.delete()
}
}
}
Write-Host "End Of Standard TCP/IP Printer"
Write-Host "Start Of WSD Printer"
Get-WmiObject win32_Printer -filter "PortName like 'wsd%'" | %{
$p = $_
$pn = $_.name
$pc = $pn | measure
if ($pc.count -gt 0)
{
$address = (Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Print\Printers\$pn\PrinterDriverData\ -Name HPEWSIPAddress).HPEWSIPAddress
if ($address -like "$port*" -and $pn -notlike "$imprimante")
{
Write-Host "The printer '$pn' is going to be removed."
$p.delete()
}
}
}
Write-Host "End Of WSD Printer"
到目前为止,脚本运行良好,计划任务也运行,但有一个问题一直存在。最后删除的打印机(或只有一台打印机时删除的打印机)仍然显示在“设备和打印机”中。
打印机似乎被“卸载”了,因为它不再可用。这是脚本前的图片(抱歉,法国环境)移除前的打印机
这是脚本之后的图片移除后的打印机
所有打印选项都消失了,但打印机仍然存在。唯一的办法就是手动删除它。
有人见过这种情况吗?我尝试使用“Rundll printui.dll”删除打印机,但没有成功。
多谢