Deleting and Recreating Printers Using a VB Script (Part 1)

This post expands on some concepts that I first touched on in this post which was about how you can create a backup script which can be run for a user’s connected printers.

On a similar note, I thought I’d throw in this one which I recently used for the migration of some users’ printers after a large office move. As the printers had moved with them and the printer name contained a code for the building it was in, the change was first carried out on the server to rename the affected queues, then the clients required attaching to these new queues to allow printing.

I originally thought whether it would be good practice to remove all network printers on the target PC (as shown in this post) but instead I decided to go for a more elegant and targeted solution (see Part 2). As is usual, the script below goes through the basics of what we need; Option Explicit, dimming variables, error handling and so on are omitted for the sake of brevity.
In this first example, let’s see how easy it is to remove all network printers from a user’s profile. OK, so let’s get started…

First off, we need to let the script know we’re talking about this PC and that we want to run a WMI query on the printers in the user’s profile. We also want to set up the objNetwork variable (as we’ll need that to add or remove network printers).

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")

Set objNetwork = CreateObject("WScript.Network")

 

Now, we want to go through that list of printers, checking if each one is a network printer and deleting it if that’s the case.

For Each objPrinter in colPrinters
    If objPrinter.Attributes And 16 Then
        objNetwork.RemovePrinterConnection objprinter.name   
    End If
Next

 

And that’s it. You’ve now deleted all the network printers on the PC. The IF statement is the magic bit as it checks whether the printer is recognised as “16” or networked.

In part 2 I’ll show how I made this framework into something a little more targeted.

Leave a comment

Your comment