Skip navigation

JSI Tip 7280. How do I print to a user's default printer in a CMD script?


If you need to print a text-based document to a user's default printer, you need to know what the default is, so you can issue the appropriate command, like one of the following:

print /d:\\<printserver>\<sharename>  <drive:>\<path>\<filename>

print /d:LPT1 <drive:>\<path>\<filename>
I have scripted DfltPrt.bat to return the logged on user's default printer. The syntax for using DfltPrt.bat is:

call DfltPrt Printer

where Printer is a call directed environment variable that will contain:

N                           - No default printer exists.
LPTn                        - Local Printer on port LPTn.
\\<printserver>\<sharename> - Shared network printer.
To print a text-based document, you would use:

print /d:%Printer% <drive:>\<path>\<filename>

DfltPrt.bat uses Rmtshare.exe and Reg.exe from the Windows 2000 Support Tools, or Reg.exe that is built into Windows XP and later.

DfltPrt.bat contains:

@echo off
if \{%1\}==\{\} @echo Syntax: DfltPrt Printer&goto :EOF
setlocal
set dflt=N
set key="HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows"
for /f "Skip=4 Tokens=2*" %%p in ('REG QUERY %key% /v Device') do set prtn=%%q
set prtn=%prtn:)=\}%
set prtn=%prtn:,=#%
for /f "Tokens=3 Delims=#" %%p in ('@echo %prtn%') do set ptype=%%p
if /i "%ptype:~0,3%" EQU "LPT" goto lcl
for /f "Tokens=1 Delims=\" %%p in ('@echo %prtn%') do set server=%%p
set prtn=%prtn:\=%
call set prtn=%%prtn:%server%=%%
set prtn=%prtn:~0,28%
set share=N
set prtn=%prtn:\}=)%
for /f "Skip=4 Tokens=1*" %%p in ('rmtshare \\%server%') do set s1=%%p&set s2=%%q&call :parse
if "%share%" NEQ "N" set dflt=\\%server%\%share%
:return
endlocal&set %1=%dflt%
goto :EOF
:lcl
set dflt=%ptype:~0,4%
goto return
:parse
set s2=%s2:~0,28%
if "%prtn%" EQU "%s2%" set share=%s1%
NOTE: I have tested DfltPrt.bat with Windows 2000 and Windows XP clients.

NOTE: See What is the current user's default printer?



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish