Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBS - Get Default Printer

Using the Wscript.Network object shown below, is there an easy way to retrieve the default printer on a machine? I know how to set the default printer, but I'm looking to get the current default printer name. I have a mixture of Windows 2000, XP, and 7 clients and don't want to use WMI for that reason.

Set objNetwork = CreateObject("WScript.Network") 
Set objLocalPrinters = objNetwork.EnumPrinterConnections
like image 620
Mark Avatar asked Feb 16 '10 14:02

Mark


People also ask

How do I set a default printer in vbscript?

Create a . vbs file (name it DefaultPrinterChanger. vbs or something else) and change the default printer name to the name of the default printer you need.


2 Answers

The WshNetwork.EnumPrinterConnections collection doesn't provide any information about the default printer. You can try retrieving the default printer name from the registry instead, though I'm not sure if it's reliable:

Set oShell = CreateObject("WScript.Shell")
strValue = "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Device"
strPrinter = oShell.RegRead(strValue)
strPrinter = Split(strPrinter, ",")(0)
WScript.Echo strPrinter


As for WMI, it's true that some WMI classes and class members aren't available on older Windows versions. For example, the Win32_Printer.Default property that indicates whether the printer is the default one, doesn't exist on Windows 2000/NT. Nevertheless, there's a simple workaround for finding the default printer on those Windows versions, which consists in checking for the PRINTER_ATTRIBUTE_DEFAULT attribute in each printer's Attribute bitmask:

Const ATTR_DEFAULT = 4
strComputer = "."

Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colPrinters = oWMI.ExecQuery("SELECT * FROM Win32_Printer")

For Each oPrinter in colPrinters
    If oPrinter.Attributes And ATTR_DEFAULT Then 
        Wscript.Echo oPrinter.ShareName
    End If
Next

This code works on later Windows versions as well.

For details, check out this Hey, Scripting Guy! article: Is There Any Way to Determine the Default Printer On a Computer?

like image 119
Helen Avatar answered Oct 23 '22 04:10

Helen


From (MSDN):

The EnumPrinterConnections method returns a collection. This collection is an array that associates pairs of items — network printer local names and their associated UNC names. Even-numbered items in the collection represent printer ports. Odd-numbered items represent the networked printer UNC names. The first item in the collection is at index zero (0).

So there is little chance to get the default printer from this collection. Sorry

Greetz, GHad

like image 2
GHad Avatar answered Oct 23 '22 06:10

GHad