Printing Documents in WSH - Shell Printing and Printing with Notepad
(Page 4 of 7 )
Now that we have a method of controlling output print devices, let’s take a look at how to send a print job. The first method uses the Windows Shell. If you open Explorer or My Computer and right-click a file in a common document format, you should see a Print entry on the context menu. This provides a quick method of printing the document without having to first open the host application.
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(strFolder)
Set colItems = objFolder.Items
For Each objItem In colItems
If objItem = strFile Then
objItem.InvokeVerb("Print")
Exit For
End If
Next
After connecting to the Explorer Shell object (Shell32.dll), use the NameSpace method to return a folder object for the folder where your file or files are located. Next, you can use an If block nested inside of a For…Next loop to locate a specific file to print.
There is no way to specify a file directly without first connecting to its parent Folder object. This is the only way to retrieve a File object for the specified file.
Finally, the InvokeVerb method is used to execute the Print command. This is effectively the same as right-clicking a file and choosing Print from the context menu. Note that this will cause an error if the selected file’s context menu does not have a Print entry.
While the Shell method above will work for most recognized file types, you may run across instances when it will not. This is especially true if files have been renamed with unrecognized extensions.
The Shell Print method will print to the system default printer.
In these cases, you can print text-based files very easily using the Notepad application. Notepad provides a simple command line that can be used to print a file to the default printer without having to open the application directly.
Set WshShell = CreateObject("WScript.Shell")
strCommand = "notepad /P " & Chr(34) & strFile & Chr(34)
result = WshShell.Exec(strCommand, 0, False)
Here again we return the WshShell object’s Exec method to execute our command line. Notice that I’ve used Chr(34) to enclose the file path in double quotes in case it contains spaces. The strFile variable may contain either an absolute or relative path to the file to be printed.
Next: Printing Word and PDF Documents >>
More Windows Scripting Articles
More By Nilpo