Networking – Create a batch file to backup and restore network printers for all users

batch filenetworkingprinter

I have an XP machine with multiple profiles. These profiles sometimes have different printers mapped to each user. Example:

  • User A has network printer 1, 2 and 5 mapped. Printer 2 is default.
  • User B has network printer 1, 4 and 8 mapped. Printer 4 is default.
  • User C has network printer 2 mapped. Printer 2 is default.

My ideal would be to poll each and every user on the machine, list all the printers they have mapped, and then strip out the duplicates so that I have a list of unique printers mapped to the machine. Ideally I'd like to see which was defaulted most often, but that's totally optional. The list then would look like:

Machine.Old

 - Printer 1
 - Printer 2 [Defaulted most often]
 - Printer 4
 - Printer 5
 - Printer 8

I would then like to restore the entire list of printers to each user on their new machine. They are migrating to a new windows 7 machine.

I've figured out how to do this for single user machines, with the following code:

Echo exporting printers
reg export HKCU\Printers\Connections %~d0\%username%\printers.reg
net use >%~d0\%username%\mappings.txt

Echo Importing Printers
reg import %~d0\%username%\printers.reg

The problem is that this works for only one user. I have an admin account, and I would like to get this to work all at once for a multiprofile machine.

Best Answer

To access the registry keys of the other users on the system you will have to load the registry hive per each user. See reg /? The user's hive file NTUser.dat will be located at the base of each user's directory. C:\Documents and Settings\<User>\NTUser.dat. Note that it is a hidden system file.

I do not have the time to create an entire report, but here is how to export the printers for all of the users. This will loop through every user directory, load their registry hive, and export the printers to a user directory at the base of the drive.

@echo off
pushd "C:\Documments and Settings\"
for /d %%A in (*) do call :ExportPrinters "%%~dpnA" "%~d0\%%~nA"
popd
goto End


:ExportPrinters <UserDir> <Target>
setlocal
set "xUserDir=%~1"
set "xTarget=%~2"
if not defined xUserDir goto :eof
if not exist "%xUserDir%" goto :eof
if not defined xTarget goto :eof
if not exist "%xTarget%" goto :eof
reg load "HKU\TempHive" "%xUserDir%\NTUser.dat"
reg export "HKU\TempHive\Printers\Connections" "%xTarget%\printers.reg"
reg unload "HKU\TempHive"
endlocal
goto :eof


:End
pause
Related Question