The Broadband Guide
SG
search advanced

How to Backup using Batch Files

2004-12-10 (updated: 2020-09-30) by
Tags: , ,

Sometimes it is useful, or even necessary to simply copy existing directories to another hard disk or network drive, rather than using more complicated backup methods. Multiple directories can be backed up comparatively easy with a simple click, by creating and running a batch file. That file can be executed manually from your desktop, can be added to startup or scheduled for periodic execution as needed.

Batch files have comparatively easy syntax and can have many uses, so this method could also be a good learning experience by example. You can simply copy the text below, and paste it into Notepad. Create a new file with either .bat or .cmd extension, rather than txt.

Here is a working example of a backup script you can modify for your needs:

@echo off
:: variables
set drive=G:\Backup
set backupcmd=xcopy /s /c /d /e /h /i /r /y

echo ### Backing up My Documents...
%backupcmd% "%USERPROFILE%\My Documents" "%drive%\My Documents"

echo ### Backing up Favorites...
%backupcmd% "%USERPROFILE%\Favorites" "%drive%\Favorites"

echo ### Backing up email and address book (Outlook Express)...
%backupcmd% "%USERPROFILE%\Application Data\Microsoft\Address Book" "%drive%\Address Book"
%backupcmd% "%USERPROFILE%\Local Settings\Application Data\Identities" "%drive%\Outlook Express"

echo ### Backing up email and contacts (MS Outlook)...
%backupcmd% "%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook" "%drive%\Outlook"

echo ### Backing up the Registry...
if not exist "%drive%\Registry" mkdir "%drive%\Registry"
if exist "%drive%\Registry\regbackup.reg" del "%drive%\Registry\regbackup.reg"
regedit /e "%drive%\Registry\regbackup.reg"

:: use below syntax to backup other directories...
:: %backupcmd% "...source directory..." "%drive%\...destination dir..."

echo Backup Complete!
@pause


The above example backs up "My Documents", Favorites, Outlook Express email/address book, (all for the current user) and the Windows Registry. It copies the files to the directory defined in the %drive% variable, or "g:\Backup". If the script is ran multiple times, it will only rewrite if the source files are newer. It will create subdirectories as necessary, and it will retain file attributes. It can copy system and hidden files.

In the above file, all lines that begin with "::" are comments. The "set drive=" and "set backupcmd=" near the top define two variables (referenced by %drive% and %backupcmd%), used a number of times throughout the file; the first being the location of the top directory where we want to backup, and the second the actual copy command with all necessary switches. All the "echo " lines in the file simpy output the line of text to the screen, and the lines beginning with %backupcmd% are the actual commands to execute.

Note that most of the folders in the above backup example are subdirectories of the %USERPROFILE%... It is possible to simply backup the entire user profile with My Documents, Favorites, Outlook Express, Outlook, etc. by backing up this one folder. Here is an example (it assumes the above "drive" and "backupcmd" variables are set):

%backupcmd% "%USERPROFILE%" "%drive%\%UserName% - profile"


Backing up Other Directories and networked PCs

You can backup other directories by simply creating more alike lines:

%backupcmd% "...source dir..." "%drive%\...destination dir..."

For example, if you'd like to backup "C:\Program Files\Microsoft Office"  to our destination "G:\Backup\MS Office" (and retain the directory structure) you'd need to add the following line to the batch file:

%backupcmd% "C:\Program Files\Microsoft Office" "%drive%\MS Office"

Here is another example, backing up the Administrator Profile on a machine on the LAN with computer name "Lianli":

%backupcmd% "\\Lianli\c\Documents and Settings\Administrator"  "%drive%\Lianli - admin profile"

Remember, you have to save the batch file with either .bat or .cmd extension, then just double-click to execute it.


Using the Current Date

Sometimes it is useful to create folders with the date incorporated in the folder name. Here is how to set the variable folder to the current date (assuming US system date format):

set folder=%date:~10,4%_%date:~4,2%_%date:~7,2%
%backupcmd% "...source dir..." "%drive%\%folder%\...destination dir..."

It is also possible to use the current time in the folder name. The following example with incorporate both the current date and time to the minute, separated by underscores. There is an extra step that cleans up possible spaces in single-digit hours in the system time:

set hour=%time:~0,2%
if "%hour:~0,1%"==" " set hour=0%time:~1,1%
set folder=%date:~10,4%_%date:~4,2%_%date:~7,2%_%hour%_%time:~3,2%
%backupcmd% "...source dir..." "%drive%\%folder%\...destination dir..."


Example - dated directories

In the example below, we first set 3 variables: drive, folder, and backupcmd. The "drive" variable defines the root directory of our backups. The "folder" takes the 2 digit day value from the current date (US date format, taking 2 digits from the date command output, starting at the 7th character), which we will use as a subdirectory. The third variable, "backupcmd" defines our backup command with the appropriate command line switches we want to use.

@echo off
:: variables
set drive=D:\Backup
set folder=%date:~7,2%
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

echo ### Backing up directory...
%backupcmd% "C:\Program Files\somedirectory" "%drive%\%folder%"

echo Backup Complete!
@pause

This example will backup the "C:\Program Files\somedirectory" folder to "D:\Backup\[dd]" where [dd] is the current day of the month.  After a month, we will have 30ish daily copies of the backup... And, because of the xcopy command line switches chosen, following backups will only overwrite files that are newer, speeding up subsequent backups. Alternatively you can add a line to delete the %folder% directory prior to executing the %backupcmd% if you prefer to start clean (and take longer).


Cleaning up

It is usually a good idea to clean up temporary files, cookies, and history from the destination backup, as applicable. It is especially useful if you're backing up full, multiple user profiles and overwriting them periodically. Since temporary files and cookies change, your backed up directories will keep increasing with unnecessary files. To remedy this, the following code can be added to the backup script, or to a separate batch file. It will automatically search all subdirectories for "cookies", "temp" and "history", and then remove those directories:

:: change to the destination drive first
G:
:: your parent backup directory
drive=G:\Backup

echo ### Searching for files to clean up...
cd %drive%
dir /s/b/ad \cookies > %drive%\cleanup.txt
dir /s/b/ad \temp > %drive%\cleanup.txt
dir /s/b/ad \history > %drive%\cleanup.txt

echo ### Deleting cookies, temp files and history from backup dir
for /f "delims=" %%J in (%drive%\cleanup.txt) do rd "%%J" /Q/S

echo Cleanup complete
@pause


Note that you need to change to the destination drive, and the main backup directory before searching for files to delete. Any sub-folders that contain "cookies", "temp", or "history" will be deleted automatically. You can test to see what will be deleted by commenting out the "for /f ....." line (just add :: to the beginning of the line, or delete it from the batch file and add it again later). If that line is not present, the file will only list all files to be deleted in the cleaup.txt file, located in the destination directory (G:\Backup\cleanup.txt in the above example).  If you add the cleanup portion to the end of your  backup batch file, you may want to remove the "@pause" line at the end of the backup portion, so everything can execute without user interacion.

Alternatively, there is a simpler one-line method of deleting specific subdirectories after backing up. The disadvantage of using this method is that you'd need another line for each separate directory to be removed... In other words, it doesn't work well when removing a large number of directories by similar names. Still, here is an example:

rmdir /s /q "%drive%\%UserName%\Local Settings\Temporary Internet Files"


See Also:  How to backup using Batch Files in Windows 10 (using Robocopy)


Notes:

    Any batch file can be interrupted with CTRL+C or CTRL+Break if needed. They can also be paused with the Pause/Break key.  Instead of backing up My Documents, Favorites, Outlook and Outlook Express files separately, you can combine it all into one line for the current user: %backupcmd% "%USERPROFILE%" "%drive%\%UserName% - profile" . The only disadvantage being that it would save temporary IE files as well (however the default location of those can be changed, or you can automate cleanup after backing up, as described above).The Registry backup in the above examples works well only for partial registry restores, it does not save the complete system state. Read this FAQ for more info.
  • Also check: Microsoft SyncToy 2.1 for folder synchronization.


  User Reviews/Comments:
    rate:
   avg:
by mohamad - 2012-08-10 19:35
hello everybody

I need a bach file can specify:
which directory to backup.
which type of files to backup eg if the user specifies java,it will copy all files with a .java suffix.
by hayland - 2012-08-11 04:59
Nevermind, I just figured out that the line goes both ways, since it already copies only modified files.

So it'd go like this, right?

%backupcmd% "\\Lianli\c\Documents and Settings\Administrator" "%drive%\Lianli - admin profile"

%backupcmd% "%drive%\Lianli - admin profile" "\\Lianli\c\Documents and Settings\Administrator"
by anonymous - 2012-08-15 12:29
This was EXACTLY what I needed! Thank you! A time stamped folder backup! I had my company's fancy backup app restore a file and wiped out my changes for that day! I will use this batch every day from now on!
by Philip - 2012-08-28 20:24
hayland, yes, pretty much it only copies modified files after the first time, so you'd have to do it both ways.
by anonymous - 2013-05-09 12:43
Is there any way to create a time stamped folder each time BUT only back up what has changed since the previous backup?

Now:
:: variables
set drive=C:\backupdocs\APTRA\APTRA_2.2_UG\v2.2.0\English
set folder=%date:~10,4%_%date:~4,2%_%date:~7,2%
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y
by anonymous - 2013-10-18 09:09
Great script, I'll use it for my home hosted gaming server ! :)
Thanks a lot!
by anonymous - 2013-10-23 06:09
Please little help.
I changed code to :
set drive=B:\zaloha
set /P source= path B:\zaloha\downloads and uses C:\test\downloads as source. Works fine, but how should I change it if the zdroj.txt have more lines? He will do just first line and I don't know how exactly %%1 works.
Can anyone help me please?
by DAMZ - 2014-12-17 06:11
i want to write a network backup .bat file, i have a nas drive in place on my network with 15 users how would i write a incremental batch backup file for all users data to be backed up onto my nas drive, my network drive is labled z and i would like to take data from the c drives which would be programme files and the user file, all users are connected wirelessly so can somebody please write a batch file code for me and i can try it.

please send me a email if you have done it if you see it in your heart
by anonymous - 2015-12-07 13:05
Does anyone know how to create a batch file that automatically backups the users document folders. It needs to check if files exist in the destination, copy only files that have changed since the last time it was ran. It will need to create any files or folders that are new since last backup. When started it should ask the user for their full name, user name, to close all files and folders, and ask if it is ok to proceed with back up. The files should back up to the users H: drive into a folder called backup. The backup directory will then be compressed to save space. A log should be updated when ever the batch file is used, logging employee name, user name, time, and date.
by anonymous - 2015-12-28 22:38
Used this batch for ages - so much easier than any other way i have come across because it just copies - don't need any software to restore.

FOR /F "tokens=1-4 delims=/ " %%I IN ('DATE /t') DO SET mydate=%%L-%%K-%%J-%RANDOM%

set backlog=C:\"backup"\DLOG%RANDOM%.txt

echo Backed up files for %username% %computername% to E: External Drive > %backlog%
echo ------------------------------------------------------------------------------------------------------ >> %backlog%
echo Backup started on.... >> %backlog%
date /t >> %backlog%
echo at >> %backlog%
time /t >> %backlog%

@echo OFF

xcopy "C:\Personal\*.*" "E:\%mydate%\Personal\" /s /i /y

echo Finished on.... >> %backlog%
date /t >> %backlog%
echo at >> %backlog%
time /t >> %backlog%
echo ------------------------------------------------------------------------------------------------------ >> %backlog%
echo System information:- >> %backlog%
systeminfo >> %backlog%
by NMitch - 2016-05-07 05:19
Hi,

I'm new to batch files, and I can't seem to get this simple backup right - any help would be appreciated.

echo off
:: variables
set drive=G:\
set backupcmd=xcopy /s /c /d /e /h /i /r /y

echo ### Backing up D:\ drive ...
%backupcmd% "D:\" "%drive%\"
echo.
echo ===============================
echo If there are no files to backup
echo you will see a message that the
echo directory could not be created.
echo ===============================
echo.
echo Backup Complete!
@pause


Thank you,
by Philip - 2016-05-07 10:15
MMitch,

Your drive variable has an extra slash at the end, that could be the issue. Try this::

:: variables
set backupcmd=xcopy /s /c /d /e /h /i /r /y

echo ### Backing up D:\ drive ...
%backupcmd% "D:\" "G:\"
by NMitch - 2016-05-10 09:54
Thanks Phillip; however, I get the following:

C:\ [user] \Desktop>set backupmd=xcopy /s /c /d /e /h /i /r /y
C:\ [user] \Desktop>echo ### Backup up D:\ drive . . .
C:\ [user] \Desktop>xcopy /s /c /d /e /h /i /r /y "D:\" "G:\"
File creation error - The parameter is incorrect.

Unable to create directory - G:\
0 File copied
Press any key to continue . . .

Here is my code:

:: variables
set backupcmd=xcopy /s /c /d /e /h /i /r /y

echo ### Backing up D:\ drive ...
%backupcmd% "D:\" "G:"
@pause

Any help would be appreciated.

Thank you,

Mitch
by Gyanendra Singh - 2016-11-29 21:56
Dear Team,

Anyone can suggest me a script i am really looking for a script that copy a daily morning and evening same one server drive file data to another server shared drive that is backup server server to store data as redundancy purpose.

Scenario :
In my bank work i have to daily manually backup pdfs data file from same location one server [primary Main server - FTP server where exctly where daily basis new files automatically create] & other server is backup server just a redundant copy of primary server to sync same primary server file as it as. I need to maintain daily date wise generated copy of pdfs files on backup server manually morning & evening.

So i request you all people who are expert please suggest me such scriot to automate data on backup servers.
I am really looking for your reply guys !!!

Thanks & regards,
Gyanendra Singh
cont 9716825926 /9212808381
mail id - gyanendra.singh2@outlook.com
by attroll - 2017-02-23 08:56
I am using the following batch file below and it is somewhat working. When I run it some files keep getting copied even though the dates and times of the files have not changed. Is there something wrong with my batch file? It's not doing it with all the files just certain ones?

@echo off
:: variables
set drive=R:\Blaze\Book\Backups

set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

echo ### Backing up directory...
%backupcmd% "C:\Book" "%drive%\%folder%"

echo Backup Complete!
@pause
News Glossary of Terms FAQs Polls Cool Links SpeedGuide Teams SG Premium Services SG Gear Store
Registry Tweaks Broadband Tools Downloads/Patches Broadband Hardware SG Ports Database Security Default Passwords User Stories
Broadband Routers Wireless Firewalls / VPNs Software Hardware User Reviews
Broadband Security Editorials General User Articles Quick Reference
Broadband Forums General Discussions
Advertising Awards Link to us Server Statistics Helping SG About