Delete al printer for a specific SessionID

After obtaining the list of Terminal Server Session ID in the previous article, now I need to delete alla printers related to this session ID.

This is the VBScript code

SessionID = 1234

Set WshShell = WScript.CreateObject("WScript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters = objWMIService.ExecQuery _
("Select * from Win32_Printer")
For Each objPrinter in colInstalledPrinters
pos = instr(objPrinter.Name, "in session")
if pos > 0 then
pos = pos + 10
if len(objPrinter.Name) >= pos + 2 then
printerID = mid(objPrinter.Name, pos, 3)
else
printerID = mid(objPrinter.Name, pos, 2)
end if
if not isnumeric(printerID) then
printerid = left(printerid,2)
end if
printerID=cint(printerID)
if printerID = sessionID then
objPrinter.delete_
Wscript.Echo "DELETED : " & objPrinter.Name
end if
end if
Next
Tags: , , ,

About author

Vittorio Pavesi