9.13. Network Printer-Related Functions
WSH provides access to connected network printers in a similar fashion to network drives . You can enumerate (list), add, and remove network printer connections. The network printers are connected to a specified printer port, such as LPT1.
|
The EnumPrinterConnections method returns a special WSH collection with a format similar to the one described for the EnumNetworkDrives method. It lists the printer port and connected network printer information.
Set objNetwork = CreateObject("Wscript.Network") Set objPrinters = objNetwork.EnumPrinterConnections( ) 'loop through and display all connected printers For nF = 0 To objPrinters.Count - 1 Step 2 Debug.Print objPrinters(nF) & _ " is connected to " & objPrinters(nF + 1) Next
The AddPrinterConnection method connects a port to a specified shared network printer.
objNetwork.AddPrinterConnection( strPrinterPort , strRemoteName , _ [ bUpdateProfile ], [ bUserName ], [ bPassword ])
Table 9-17 lists the parameters for the AddPrinterConnection method.
Parameter | Description |
---|---|
strPrinterPort | Local drive letter to connect the network share to; e.g., LTP1:. |
strRemoteName | Name of remote shared printer in UNC format; e.g., \\server\printername . |
bUpdateProfile | Optional Boolean parameter that indicates if printer connection is remembered in future sessions. |
strUser | Optional username to use when connecting to remote printer. |
strPassword | Optional password to use when connecting to remote printer. This is used with the strUser parameter. |
For example:
Set objNetwork = CreateObject("Wscript.Network") objNetwork.AddPrinterConnection "LPT2", "\training_06\laserjet"
The SetDefaultPrinter method sets the default Windows printer. This method uses the printers specified under the Printers icon under Control Panel, not the printers connected using the AddPrinterConnection method. Its syntax is:
objNetwork.SetDefaultPrinter( strPrinterPort )
The strPrinterPort parameter specifies the UNC path of the printer you wish to make the default printer. This printer must be defined under Control Panel Printers.
objNetwork.SetDefaultPrinter "\thor\laserjet"
The RemovePrinterConnection method disconnects connected network printers:
objNetwork.RemovePrinterConnection strName , [ bForceDisconnect ], [ bUpdateProfile ]
The RemovePrinterConnection method has two optional parameters, the first being a Boolean bForceDisconnect flag. If set to True, it will attempt to forcefully disconnect the printer. The bUpdateProfile parameter specifies whether the user 's profile is to be updated.