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
The Broadband Guide
SG
search advanced
 Username:
 Password:
Register
 forgot your password?

How to Backup using Batch Files

2004-12-10 13:03 by
Tags: backup, batch file, script

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"

 

 

Notes:

  • Any batch file can be interupted 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 GC - 2009-12-22 04:40
Thanks! Your date format stuff helped me.


Regards,
GC
by luismx - 2010-04-07 11:47
by anonymous...
.... I do want to add a command to tell it to copy ONLY what has been changed since the last backup.
....

By adding /D will not remove unchanged files from destination folder.

Im looking for a command for daily backups, but only for modified files. Any one have some like that?

TIA.
by anonymous - 2010-05-03 18:03
Philip,
Thank you for very helpful article
Still can't make it work... maybe you can help?

If I want to rename a folder when it's backed up depending on the date, for example I have a folder with files that are populating every day in C:\CAT and I want to make a backup of it to D:\CAT but change the folder name to "CAT_dd_mm_yyyy" what do I have to do?

TIA

Michael
by Philip - 2010-05-04 17:34
Michael, you'd have to use something like:

set drive=D:\
set folder=CAT_%date:~7,2%_%date:~4,2%_%date:~10,4%
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

echo ### Backing up directory...
%backupcmd% "C:\CAT" "%drive%\%folder%"
by anonymous - 2010-05-05 10:27
Philip,

Thank you for the reply.
One more question, if you have some time…

If I have several folders to backup is it possible to make batch file to take original name of the folder ( CAT, MON or SIM), add date to it and copy it?

Something like

set drive=D:\
set folder=”Original name of the folder”_%date:~7,2%_%date:~4,2%_%date:~10,4%
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

echo ### Backing up directory...
%backupcmd% "C:\CAT" "%drive%\%folder%"
%backupcmd% "C:\MON" "%drive%\%folder%"
%backupcmd% "C:\SIM" "%drive%\%folder%"

Thank you

Michael
by Philip - 2010-05-05 10:53
Michael, there are more elegant/complex solutions, but since you're already typing the folder names once, the simplest solution would be something like:

set drive=D:\
set folderdate=_%date:~7,2%_%date:~4,2%_%date:~10,4%
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

echo ### Backing up directory...
%backupcmd% "C:\CAT" "%drive%\CAT%folderdate%"
%backupcmd% "C:\MON" "%drive%\MON%folderdate%"
%backupcmd% "C:\SIM" "%drive%\SIM%folderdate%"
...
by anonymous - 2010-05-05 11:44
Thank you Philip,

It will work for me, but if you want to share other solutions, I am all ears.. :-)

Again, thank you for your help and time

Best regards,
Michael
by Philip - 2010-05-05 12:26
Michael, alternatively you can use a loop, something like:

set drive=D:\
set folderdate=_%date:~7,2%_%date:~4,2%_%date:~10,4%
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

for %%i in (CAT MON SIM) do (
%backupcmd% "C:\%%i" "%drive%\%%i%folderdate%"
)


The variable %%i will be substituted by the folder names (separated by spaces or commas in the for loop)
by anonymous - 2010-05-06 13:25
Thanks, Philip,

If CAT( or other) folder locating not at the root directory of drive C but far, far away in subdirectories, do I need to type full path to it? I think I do.
for %%i in (CAT MON SIM) do (
And when batch file is pasting it will paste full path.

Is there any way to paste folder without the path?
That is what I was thinking about when was trying to set folder name in:
set folder=”Original name of the folder without the path to it”_%folderdate%
where %folderdate% is =_%date:~7,2%_%date:~4,2%_%date:~10,4%

You think it is possible?

TIA
Michael
by Philip - 2010-05-06 13:54
You can put any common parent folder in the %backupcmd% "C:\... line

Any partial pats/subfolders that are not common would still have to be entered in the "for..." line for each element.

For simple troubleshooting, you can prepend "echo " to the %backupcmd% line, so it would print the actual folders on the command line. You can then see exactly what it is attempting to backup and where.
by anonymous - 2010-05-06 19:23
Thanks,

I will continue to experiment… :-)
by HelloMen - 2010-06-18 11:15
Hi Guys,

I am trying to prepare myself with a system to backup files for the end users.
But I am kind of confused on the lines...
Can anyone please help me on this ?

The Option 2 and 3 does not work for the moment.

*********


CLS
:MENU
@ECHO OFF
@ECHO
@ECHO ***************************************************************
@ECHO * Company name *
@ECHO * *
@ECHO * BACKUP tools C: - Outlook PST + Personal Data *
@ECHO * To leave this tools, push "Ctrl C" *
@ECHO * Version 1.1 - XXX - June 2010 *
@ECHO ***************************************************************
ECHO.
ECHO ...............................................
ECHO PRESS 1 or 2 or 3 or to select your task, or 0 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Export "Favorites" from COMPUTER to PERSONAL DRIVE (Z:)
ECHO 2 - Export "My Documents" from COMPUTER to PERSONAL DRIVE (Z:)
ECHO 3 - Export "Outlook" from COMPUTER to PERSONAL DRIVE (Z:)
ECHO 9 - Import Favorites from PERSONAL DRIVE (Z:) to COMPUTER
ECHO 0 - EXIT
ECHO.
SET /P M=Type 1, 2, 3, or 0, then press ENTER:
IF %M%==1 GOTO EXPORT
IF %M%==2 GOTO EXPORT2
IF %M%==3 GOTO EXPORT3
IF %M%==9 GOTO IMPORT
IF %M%==0 GOTO EOF
:EXPORT
XCOPY "%userprofile%"\Favorites\*.* Z:\BACKUP\Favorites\ /S/Y
GOTO MENU
:EXPORT2
XCOPY C:\USers\"%userprofile%"\My Documents\*.* Z:\BACKUP\My Documents\ /S/Y
GOTO MENU
:EXPORT3
XCOPY "%userprofile%"\Local Settings\Application Data\Microsoft\Outlook\*.* Z:\BACKUP\Outlook\ /S/Y
GOTO MENU
:IMPORT
XCOPY Z:\BACKUP\%userprofile%"\Favorites "%userprofile%"\Favorites\*.* /S
GOTO MENU
by Philip - 2010-06-18 11:24
You need to put directory names that contain spaces in quotes... Try:


:EXPORT2
xcopy /s /y "C:\Users\%userprofile%\My Documents" "Z:\BACKUP\My Documents"
GOTO MENU
:EXPORT3
xcopy /s /y "%userprofile%\Local Settings\Application Data\Microsoft\Outlook" "Z:\BACKUP\Outlook"
by anonymous - 2010-07-26 16:56
Is it possible to create a batch file that will copy files from any directory with out having to specify said directory. For example, if I wanted to copy all *.doc files from anywhere on the c:\, is there a command that can do that? Or are we limited to telling the batch file which directory to search from.

I am trying to create a generic batch file that can find all of the normal files one would want to save and move them to another drive. Since not all people put their docs, pics, music, etc in the same places it would be nice if the batch file could just find the files anywhere on the hard drive with a wild card + extension name and move it.
Thanks!
by anonymous - 2010-09-29 12:42
hello,

I came across this while trying to improve upon my own backup scripts that do pretty much most of what was outlined in the original post. However, I have come across a new problem that I can't quite solve - cleaning up!

Example: The My Documents folder is backed up every night to an external drive. But today I thoroughly went through the My Documents folders and files and rearranged them, moved many into new sub-folders and deleted quite a bit of data from all of the My Documents folders and sub-folders.

Problem: How can I write the backup script to do a comparison between the main My Documents folder and the backed up My Documents and delete everything from the backed up My Documents folder thats no longer in the main (and rearranged) My Documents folder?

IE: C:\...\My Documents\TempFolder also exists on the backup G:\My Documents\TempFolder, but has now been deleted off of the C: drive, how can the script be written to automatically see this difference and delete it off of the backup on the G: drive?
by Felix88 - 2010-12-25 17:44
I'm running this simple backup file, but I need the delete line to only run if it finds any new files in the mobile applications folder.

The reason for deleting the file, is the backup cant tell if files have changed names, which with iphone apps happens when versions change.

So, I need it to scan the current backup, and live folder. If it finds any differences, delete the backup, and copy it all again.

Any ideas?

ps: Also, is my current script right?

@echo off
:: variables
set drive=I:\iTunes Backups
set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

echo ### Deleting Mobile Apps
rmdir /s /q "%drive%\iTunes Backups\iTunes\iTunes Media\Mobile Applications"

echo ### Backing up directory...
%backupcmd% "D:\iTunes" "%drive%\iTunes"

echo Backup Complete!
@pause
by deepak - 2011-02-19 08:55
please give solution for incrementel backup using bat file
by kailas - 2011-03-02 07:16
Hey guys could u provide me with a batch file to copy desktop,my documents and favourites of a user to another drive along with a log file which have the date nd time of copying the documents.Im not kinda familiar with batch commands,so plz help..
by Gary - 2011-03-17 15:06
I used you script and it ran great on windows xp. I need to port this over to windows 7 what changes do I need to make?
by Philip - 2011-03-17 16:42
Most of the directories are still valid in Windows 7

I stop Outlook while backing up outlook.pst , and use the new folder names, i.e. "AppData" instead of "Application Data", "Documents" instead of "My Documents", "Pictures" instead of "My Pictures"... But the old ones work as well, Windows 7 has shortcuts that point to the same locations for backward compatibility.

Here is how I stop Outlook while copying the pst file if someone is interested:

:: stop Outlook
taskkill /im outlook.exe
%backupcmd% "C:\Users\%user%\AppData\Local\Microsoft\Outlook" "%drive%\%user%\AppData\Local\Microsoft\Outlook"
start outlook.exe
by jmihm - 2011-12-05 23:52
Philip,
Great script thanks alot I will be modifying it for my needs. I noticed that you use the /c switch to turn off error reporting but was wondering if you may have advice on getting it to write any possible errors that it encounters to a txt file
thx,
Jmihm
by Masoud - 2012-02-02 00:52
Dear Philip , Hi
Great and helpfull job.
I am using script wich enters date in backup folders name.
But I have to delete old folders to save disk space.
Can you explain how can I delete old backup files automatically.
For example removing backup folders wich are older than one week automatically.
Thanks.
by Rafih - 2012-03-06 05:36
Hello, i have been working with batch commands since two months and i have a done a small program that backup all the files in my laptop to a server over a network, with making an archive of seven days.
If anyone can provide me with some help of, how to do a log file of all the errors, if any, and locate it on the server.
Thanking you in advance
by Mani - 2012-05-01 04:00
Hi Philip, its very help to me to run the script, I used /D. Still my doubt is my data is mounting up day by day. I don't need to mount up my data at destination. If I delete the data at source it should also be delete the particular file which I deleted at source.. so please help me for my problem.


Thanks in advance
by hayland - 2012-08-09 12:39
Hi there, thanks for this absolutely fantastic guide. I have a bit of a problem though, that I can't solve by myself.

We have on our office two computers that both use same network drive. I would need a backup batch that would check which file is newer, the one on the computer or the one on the network drive, and then copy it. Both computers would use scheduled tasks to run the batch everyday, so that the files would be up to date on both the computers and the network drive.

At the moment, I'm running the batch presented on this guide on one of the computers. Both computers use a patch to map the network drive. The other computer is running win 7 while the other one runs win xp.

So here is what I need:

(not code)

if file is newer on the computer, copy it to the network drive
if file is newer on the network drive, copy it to the computer
if file hasn't been modified, skip to a next file.


Thanks!