Printing Documents in WSH - Setting the System Default Printer
(Page 3 of 7 )
Now we’ll take a look at ways of setting the system default printer setting. This will allow us to control what printer to use in cases when we cannot specify one directly.
Set WshNetwork = CreateObject("WScript.Network")
WshNetwork.SetDefaultPrinter(strPrinter)
The simplest method of setting the default printer relies on the SetDefaultPrinter method of the WshNetwork object. It accepts a single parameter which is a valid UNC path to the printer to be used.
The next method uses WMI to set the default printer and is almost exactly the opposite of the script we used to determine the current system setting.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer _
& "rootcimv2")
Set colInstalledPrinters = objWMIService.ExecQuery _
("Select * from Win32_Printer Where Name = '" & strPrinter & "'")
In this case, we’re querying the Win32_Printer class for a specific printer. The strPrinter variable should contain the name of an installed printer exactly as it is listed by the sample script at the beginning of this article.
Printer names are defined by their drivers. The driver name is taken from the .inf file used to install the driver. You can see this name in the Printers and Faxes Control Panel applet or in Device Manager with “Show hidden devices” enabled.
This WMI query will return a collection of printer objects that should again only have a single member unless there are multiple instances of the same printer installed.
For Each objPrinter In colInstalledPrinters
objPrinter.SetDefaultPrinter
Next
The printer object then provides the SetDefaultPrinter method, for a quick way of changing its Default property to True.
You can also set the system default printer by using the system API with the help of rundll32 on the command line.
Set WshShell = CreateObject("WScript.Shell")
strCommand = "rundll32 printui.dll,PrintUIEntry /y /n" & strPrinterUNC
result = WshShell.Exec(strCommand)
This method uses the WshShell object’s Exec method to run the appropriate command line. The strPrinterUNC variable should contain a fully qualified UNC path to an installed printer.
Regardless of whichever method you choose to use, any time you set a printer as the default, any other installed printers will automatically have their default value set to False.
One final method of setting the default system printer would be to manually write the registry key that you saw previously. I’m not providing an example of this since it’s best to avoid writing directly to the registry from an unattended script whenever possible.
Next: Shell Printing and Printing with Notepad >>
More Windows Scripting Articles
More By Nilpo