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 erwino - 2008-09-22 10:02
Hi there, I have been reading these comments with interest and have been trying some of the code. Can anyone help me with the following:
on our server (Microsoft Server 2003, standard edition, service pack 1) when I execute the batch file with 'echo date %date%' I get the following result: date 09.on.
on my XP machine I am getting the expected result of: date (22/09/2008)
What is going on? When I type 'date' into the command prompt I am getting today's date and the question for entering the new date...
Thanks
by jrpell - 2008-09-30 18:46
Lesson on this stuff is great. Thanks for the info as I'm really starting to learn a lot on this stuff. Now, is there anyway to use this to do an incremental backup? I want to get my fullbackup, but then tell this to just get what's changed or is new since it was last backed up. Anyone have the code or could give any direction?
by Philip - 2008-09-30 19:44
Here is the date format on Windows Server 2003:
C:\...> echo %date%
Tue 09/30/2008

So, the month is 2 digits starting at the 5th character, day is starting at the 8th character, and year starts at the 11th character.
by jrpell - 2008-09-30 22:06
Nevermind my question above. I read about the switches and see that the /d means it will only backup if the file is newer than what's already there. I'm backing up about 5 gigs worth of data right now across a small network and it's working great! Thanks!
by kearybr - 2008-10-13 14:06
How about backing up an mp3 player? Can this command file be modified to specify a usb device as the source file? Looking around in Device Manager I found my mp3 player under Portable Devices, and opening Properties then details, found data for my player under Device Instance Id, Hardware Ids, Compatible Ids, Matcing Device Id, Service, Enumerator and Capabilities. Would I use one of those ids in place of the drive spec? Which one?
by anonymous - 2008-10-14 05:41
Sir,

Actually i want to take 1 file from 1 system to another system & this process for every one hour.

Please kindly he me in this.

Rgds,
Murthy.
by Philip - 2008-10-14 09:28
If the mp3 player is accessible from command prompt / Windows Explorer, then it would be as easy as specifying the correct drive/directory.
by kearybr - 2008-10-15 13:54
Correct, that would be simplex. However my player does not show up on the tree as a drive letter, but by its name. I tried to access the player using subsequent drive letters (f, g, h, i ...) without result. That's what led me into Device Manager and the ids I quoted in my post.

I have not tried clicking on the device and mapping it to a drive. Yathink?
by JhuLzzz - 2008-10-22 21:43
Hi!!! i just a newbie exploring about the batch file and etc.,,sir!!
what if a command prompt is disabled....is there any way to run backup.bat???...
by sixxkilur - 2008-10-24 00:16
I haven't had much luck with it
heres my script

@echo off


set vbsource=j:\wamp
set vbdest=J:\vbbackups
set vbcmd=xcopy /s /c /d /e /h /i /r /y
set vbtxt=vbulletinfilelist.txt
set fullvbcmd=%vbcmd% "%vbsource%\www\" "%vbdest%\www" "%vbdest%\%vbtxt%"
set ifvbcmd=%fullvbcmd%

echo ### Setting Vbulletin Source Directory to %vbsource% ###
echo ### Setting Vbulletin Destination Directory to %vbdest% ###
echo ### Setting Backup Process Command to %vbcmd% ####
echo ### Setting Up Full Command Process to %ifvbcmd% ###

echo ### Vbulletin Forum Dir and Sub Directories...
%fullvbcmd%



echo Backup Complete!
@pause


i keep getting this error
J:\vbbackups>vbback.bat
### Setting Vbulletin Source Directory to j:\wamp ###
### Setting Vbulletin Destination Directory to J:\vbbackups ###
### Setting Backup Process Command to xcopy /s /c /d /e /h /i /r /y ####
### Setting Up Full Command Process to xcopy /s /c /d /e /h /i /r /y "j:\wamp\www\" "J:\vbbackups\www" "J:\vbbackups\vbul
letinfilelist.txt" ###
### Vbulletin Forum Dir and Sub Directories...
Invalid number of parameters
0 File(s) copied
Backup Complete!
Press any key to continue . . .

have tried many diff ways
no luck
any help would be great
by Philip - 2008-10-24 15:41
Your problem seems to be in this line:
set fullvbcmd=%vbcmd% "%vbsource%\www\" "%vbdest%\www" "%vbdest%\%vbtxt%"

You have 3 directories listed, I'm not sure what you're trying to do with it. The syntax should something like:

set fullvbcmd=%vbcmd% "%vbsource%\www\" "%vbdest%\www\"

Both the source and destination should be directories.
by Jess - 2008-11-06 15:56
This batch script if wonderful. Now I am looking for something to copy only new or modified files from one (old server) to the new server. Any ideas?
by Philip - 2008-11-06 19:16
The switches on the xcopy command in this example is set so that it will only copy new/modified files if saving to the same destination directory, so after the first backup it will only be updated.
by fcm - 2008-11-16 19:07
Excellent tutorial.

One request...

If a computer has more than 1 user on a machine, can it parse out the username from the C:\Documents and Settings\ directory listing?

That way I could make sure to grab all user folders regardless of who is running the batch file.

Thanks!
by Badaki - 2009-02-20 18:15
works great ! Thanks a lot, i should have done this much earlier, at least before i lost 200gb of data :-)
by vijay - 2009-03-10 08:44
Hello sir,

I have a direcotry in c:\ drive that is c:\do\spool, i want to
copy all files from the above directory, i tried several times
to change batch file as per my requirement, but i could not get
answer

please guide me
by anonymous - 2009-03-20 22:22
How to replace XCOPY with ROBOCOPY?

Thanks heaps =)
by thelastrewind - 2009-04-03 13:06
I have a problem that I was wondering if someone can help me with when using this batch. I have edited the batch to match my needs and it's working great. But now what I need to do is copy files from a directory that is on a CD (that part is fine) and put them into a destination path that contains a hidden directory. When I change Windows view settings to view hidden files/folders, my batch works flawlessly. However, when I hide files/folders, the batch errors saying an invalid destination.

Any tips?

Thanks,
Chris
by thelastrewind - 2009-04-04 09:44
I was able to figure out my problem. It didn't occur to me while I was wrapped up in it, but once I stepped away from it for a little while, it dawned on me to just use the ATTRIB command to change the hidden attribute, and then change it back to hidden after the copy was done.

Thanks, great batch file!
by Dimos - 2009-06-12 06:57
Hi,

The script is great.
I have one question. How can I make it to backup only on odd or even dates?
Thanks,

Dimos
by anonymous - 2009-07-22 08:57
Hi, I'm currently using this template to backup my hard drive and I've got the /d command so it will only replace updated files from my main drive to the backup drive. But is there any command to compare a folder and the backup version and delete any files from my backup which have been deleted/renamed/whatever from the main so I've got a complete mirror?

Thanks.
by Philip - 2009-07-22 11:51
There is no switch/command that I'm aware of to compare and delete files in the backup folder that have been removed from the original...

It may possibly be accomplished by a script that walks all files and compares them, by periodically deleting the backup directory to remove stale files, or by using alternating/multiple backup directories.

Keep in mind that if a user accidently deletes files, it may be a good idea for those files to remain in the backup directory for a period of time facilitating recovery.
by WerKKill - 2009-08-06 07:44
Even with the /d parameter all files are copied regardless of when the files were last edited. Any idea why? I'm backing up to a network hdd in Windows XP Pro.
by WerKKill - 2009-08-06 08:16
Actually, if I edit the files in the destination and then run the batch file it does not copy the edited files, but if the source and destination files have the same modification date all files are copied. Any ideas?
by anonymous - 2009-11-17 08:06
Use GOTO
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