PowerShell - 从打印服务器中删除打印队列

时间:2012-09-27 12:41:20

标签: powershell windows-server-2008 wmi powershell-v2.0 windows-server-2003

我有一台打印机服务器,可以容纳大约1000台打印机。我想删除其中一个。

我目前正在使用此命令:

$p = Get-WmiObject -Class Win32_printer -ComputerName $server -namespace "root\CIMV2" -filter "name='printer0456'"

它有效,找到打印机,然后我可以使用此命令删除它:

$p.delete()

但令我感到震惊的是,第一个命令找到打印机需要2-3分钟。对我而言,它完全有意义。

我做错了什么,或者其他什么我可以用来更快地删除打印机?

编辑:检查我的回复

这样,它只会在找到正确的打印机之前获取,而不是解析整个打印机列表。

6 个答案:

答案 0 :(得分:1)

您应该使用WMI加速器来加快对WMI的查询速度。

$PrinterInstance = [wmi]"\\$CentralServer\root\cimv2:Win32_Printer.DeviceID='$PrinterName'"

DeviceID是WMI数据库中的索引值,默认情况下,DeviceID应与打印机名称相同。

答案 1 :(得分:0)

它的WMI查询成本,因此缓存结果。拉出集合中的所有打印机。过滤集合并删除您想要的打印机。

$printers = gwmi Win32_printer -ComputerName $server -namespace "root\CIMV2"

$del = $printers | ? { $_.Name -eq "printer1"}
$del.delete()
$del = $printers | ? { $_.Name -eq "printer6"}
$del.delete()
$del = $printers | ? { $_.Name -eq "printer89"}
$del.delete()

您可以使用-like-match来过滤名称相似的打印机。像这样,

$printers = gwmi Win32_printer -ComputerName $server -namespace "root\CIMV2"

$del = $printers | ? { $_.Name -match "printer10[1-3]" } # Match printer101..103
$del | % {$_.delete()}

答案 2 :(得分:0)

我找到的临时解决方案

$p = $null
Get-WmiObject -Class Win32_printer -ComputerName $server|ForEach-Object{
    if($_.name -eq "printer0456"){
        $p = $_
        break
    }
}
if($p -ne $null){
    $p.delete()
}

答案 3 :(得分:0)

$p = gwmi win32_printer | ? {$_.name -match "PrintServer"} | % ($i in $p) {$i.delete()}

这将仅删除名称路径中具有以下打印服务器名称的打印机。

答案 4 :(得分:0)

$PrintersTodelete = Get-WmiObject -Class Win32_printer -ComputerName $server -filter "name='printer0456'"
 if($printersToDelete){
     Foreach($printer in $PrintersTodelete){
         $printer.delete()
      }
 }

答案 5 :(得分:0)

<#
    Delete printers on remote servers using csv list(server,printer)
    Note: For queues with job(s), they will be stuck in a "deleting"
    state and you must clear the job(s) manually, the queue will delete
    after that. Or, you will need to write in code to stop spooler and
    delete jobs from \spool\printers. Not a big enough deal to warrant
    risk of spooler not starting back up.
#>

$InCSVPath = "\\path_to_list_file\printerstodelete.csv"

$csv = Import-Csv $InCSVPath
foreach($item in $csv){ 

       $server = $item.Server

       $printer = $item.Printer 

       $a = Get-WmiObject -Class Win32_printer -ComputerName $server -Filter "name= '$printer'"

        if($a){

             "Deleting Printer: " + $a.Name #

              $a.Delete()

         }

         else{

               "could not delete: "+$printer

         }

}