Just a short post today to demonstrate how easy it is to delete a printer from a PC executing some simple WMI code via VBA.
If you follow my blog at all, by now you are fully aware that WMI can easily retrieve information regarding pretty much any aspect of your PC: Hardware, Software, Events, …, but it can do so much more. Did you know it can also make changes to your PC! It can install, configure and even delete pretty much anything as well. So let’s explore a first simple example, the printer.
'---------------------------------------------------------------------------------------
' Procedure : WMI_Printer_Delete
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Remove a Printer from the local PC
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Early Binding -> Microsoft WMI Scripting VX.X Library
' Late Binding -> None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sPrinterName : Name of the printer to remove
'
' Usage:
' ~~~~~~
' ? WMI_Printer_Delete("Brother HL-2130 series")
' Returns -> True/False
'
' Revision History:
' Rev Date(yyyy-mm-dd) Description
' **************************************************************************************
' 1 2023-03-02
'---------------------------------------------------------------------------------------
Public Function WMI_Printer_Delete(ByVal sPrinterName As String) As Boolean
On Error GoTo Error_Handler
#Const WMI_EarlyBind = False 'True => Early Binding / False => Late Binding
#If WMI_EarlyBind = True Then
Dim oWMI As WbemScripting.SWbemServices
Dim oPrinter As WbemScripting.SWbemObject
#Else
Dim oWMI As Object
Dim oPrinter As Object
#End If
Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set oPrinter = oWMI.Get("Win32_Printer.DeviceID='" & sPrinterName & "'")
oPrinter.Delete_
WMI_Printer_Delete = True
Error_Handler_Exit:
On Error Resume Next
Set oPrinter = Nothing
Set oWMI = Nothing
Exit Function
Error_Handler:
If Err.Number <> -2147217406 Then 'Printer Not found
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Source: WMI_Printer_Delete" & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
End If
Resume Error_Handler_Exit
End Function
and as shown in the function header, we can simply call it by doing
? WMI_Printer_Delete("Brother HL-2130 series")
which then returns:
True, if the printer was successfully deleted
False, if the printer wasn’t deleted (this also applies if the specified printer isn’t found)
