Monday, February 17, 2014

How To Remove All the Network Printers on a Computer?


For better or worse, here’s the Windows 2000 script:
Const NETWORK = 22

Set objNetwork = CreateObject("WScript.Network")

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")
     
For Each objPrinter in colPrinters
    If objPrinter.Attributes And NETWORK Then 
        strPrinter = objPrinter.Name
        objNetwork.RemovePrinterConnection strPrinter
    End If
Next
This time around we start out by defining a constant NETWORK and setting the value to 22; we’ll use this constant to help us determine whether a given printer is a network printer or a local printer. After that we create an instance of the Wscript.Network object, the WSH object we can use to remove printers from a computer.
From there we bind to the WMI service (remember, local computer only) and then use the following line of code to return a collection of all the printers on a computer:
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")
Now, you’re right: we don’t want to remove all the printers on a computer, do we? Instead, we want to remove only network printers. That’s why, after setting up a For Each loop to walk through the collection of printers, we run this line of code:
If objPrinter.Attributes And NETWORK Then
As it turns out, the Attributes property is a “bitmask” property, a property that can contain more than one value.
Bitmasks are composed of “switches” that can be either on or off; for example, the Attributes property has a “switch” with a value of 22 that tells us whether a printer is a network printer. If this switch is on then we have a network printer; if this switch is off then we have a local printer. The preceding line of code simply checks to see if the Network switch is on. If it is, we assign the printer Name to a variable named strPrinter, then use this line of code to delete that printer connection:
objNetwork.RemovePrinterConnection strPrinter
From there we loop around and repeat the process with the next printer in the connection. It’s not the most elegant script in the world, and it is restricted to the local machine (making it a candidate for inclusion in a logon script) but it works.
By the way, local printers have their own switch, one with a value of 100. How does that help you search for local printers? Well, to search for local printers you can first define a constant named LOCAL, with a value of 100:
Const LOCAL = 100
And then you can check each printer on the computer to see if the local switch is on or off:
If objPrinter.Attributes And LOCAL Then

No comments:

Post a Comment