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 Philip - 2007-05-09 12:44
I'm not sure what the Swedish date format is exactly... You can see it by typing "date" in command prompt. Then I'd compare it with the batch file, you can print the output, to see what you get... Something like:

SET dateNtime="%date:~0,2%_%date:~3,2%_%date:~6,6%"
echo %dateNtime%
@pause
by Loranga - 2007-05-10 06:29
Thanks for your quick reply

Date in cmd gives me:
The current date is: 2007-05-10
Time in cmd gives me:
The current time is: 12:25:13,21

When I run my bat file (with echo) it shows:
set dateNtime = "20-7--5-10_12-26"

I have problem understanding the code set dateNtime = ... in the bat
by Philip - 2007-05-10 08:45
SET dateNtime="%date:~0,2%_%date:~3,2%_%date:~6,6%"

The above line takes part of the date command output "The current date is: 2007-05-10" (starting with the actual date, and counting from zero). For example, the %date:~0,2% part means: start from the "0" character position, and read 2 characters. In your date output (2007-05-10) that would be the first two characters, "20". There are two more sections taking parts of the date (2007-05-10) in the line above, separated by underscores.

To fix your output, try:


SET dateNtime="%date:~0,4%-%date:~5,2%-%date:~8,2%_%time:~0,2%-%time:~3,2%"

I hope this helps
by Loranga - 2007-05-10 09:34
Thanks it's working!

One more thing, If you live in Sweden like me and want to use Å Ä Ö in your file it might be good to use edit (type edit in dos window). That way you will automaticly get the right characters for ÅÄÖ
--
set folder=%date:~8,2%
--
by s43s - 2007-05-20 08:45
Let me start by saying I'm new to the batch file game (and late to it as usual :). I may be in the wrong thread to post and if so I apologize. Thank you for your assistance.

I am using the following to backup a folder and add the date to it. The folder name and date work fine but the contents do get backed up, why? Any assistance is appreciated.

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

echo ### Backing up directory...
%backupcmd% "C:\inetpub\wwwroot\foldername." "%drive%\%folder%\c:\inetpub"
by anonymous - 2007-05-31 10:48
Thanks alot for sharing this very useful script. I could run this successfully after adding to the scheduled jobs on windows, although I see the flash of the console whenever the batch script is run. I dont want to see the console, I want this script to run in background without users knowledge. What should I do to stop seeing the flash of the console?
by serenetty - 2007-06-06 02:36
Hi,
How can i backup my .txt files monthly? The txt file will be written everyday, but i want to backup all these files to another location base on monthly basis. Any idea?
by mukeshwani - 2007-06-13 09:31
Does the script or specifically the xcopy command perform deletes? For example, if a file or directory is deleted in the source, it gets deleted in the destination as well.

Thanks,
Mukesh
by anonymous - 2007-09-02 15:34
How does one answer prompts in dialog boxes for windows programs in a batch file?

I wish to run the following line in a batch file before it goes and does the rest of the batch file. But when the program finishes a dialog box comes up with an OK prompt in it. The batch file will not continue until that prompt is answered by clicking on it. How do I answer the "OK" prompt from within the batch file without user interaction?

D:\"Program Files"\Yamicsoft\"WinXP Manager"\1-ClickCleaner.exe

defrag -f -v c:
defrag -f -v d:
by matmax - 2008-01-30 01:10
@echo off
:: variables
set drive=c:\Backup
set backupcmd=xcopy /f

%backupcmd% "%Administrator%" "%f%\%Administrator% - Administrator"


echo Backup Complete!
@pause

This is wat the script i ran from my desktop to copy all my c drive to the f drive administrator is my profile and the username is also administrator

When i try to execute it says o file copied and
Invalid number of parameters
0 File(s) copied
Backup Complete!
Press any key to continue . . .
by matmax - 2008-01-30 01:14
I tried the same but not able to run succesfully the error i got is Invalid number of parameters
0 File(s) copied
Backup Complete!
Press any key to continue . . .

I am trying to copy my c drive administrator profile to f drive

Please some one help me
I will be so thankful

the script was
@echo off
:: variables
set drive=c:\Backup
set backupcmd=xcopy /f

%backupcmd% "%Administrator%" "%f%\%Administrator% - Administrator"


echo Backup Complete!
@pause

Help me
by Johan - 2008-02-06 02:11
try using:
set folder=%date:~0,3%
in a batchfile. This wil give you the current day in the variable %folder%

Good luck
by anonymous - 2008-02-12 10:01
hi
i have used this script it works fine.
but how can i put the backup in a new folder everyday.
by Paul Pigeon - 2008-02-19 08:26
I've successfully used this article to generate a batch file that works for me ... so sincere thanks to all you guys ... I just need to go one extra step if that's possible?

As I am backing up my files to a USB flash drive that could perhaps change its drive letter assignment depending on which USB port I use and what other hardware is installed I need to be able to vary the drive letter in the command "set drive=E:\Backup"

I perhaps want a prompt to appear asking me to type in a single letter e.g. E. F, G, etc

Any ideas on how I achieve this?
by Mike in OKC - 2008-02-21 14:24
First off thanks for sharing the code. I had something a bit more cryptic and not quite as clean as your code.
However, I do still have one need that I have not been able to find ANY resolution for and that is a way to resolve the names of the individual profiles on the computer. I want to back up any users and the administrators folders under Documents and Settings\ and not back up the all users and NOT the LocalService, NetworkService, DefaultUser, etc... Also, every PC will have different usernames of course so I would have to change the batch file with every computer. I understand that I can log on to each profile and run it that way but some of our users profiles become corrupt or are locked down and can't run this type of command.
I appreciate your help and offer a sincere thanks.
Mike
by chris - 2008-02-25 00:18
works great, however i still haven't found an easy solution on how to get rid of files that are deleted from the source.

does anyone have any ideas on this?

chris
by Philip - 2008-02-25 19:39
The easiest solution is to delete the destination (sub)directory periodically.

Another option would be to make a batch file to delete files not accessed recently from the destination directory.
by anonymous - 2008-04-10 09:42
I'm trying to create a batch file that will automatically remove files from a directory based on the date of the file. I haven't been able to find anything that does this. Any help would be appreciated.

Thanks,
nick
by Ben - 2008-05-02 22:20
Is there any way of outputting a text file with a log of the backup in it?
by anonymous - 2008-05-03 13:03
@rem --- prepare and roll the folders,
@mkdir 1
@mkdir 2
@mkdir 3
@mkdir 4
@mkdir 5
@mkdir 6
@rmdir /s /q 7 || goto DirectoryError
@rename 6 7 || goto DirectoryError
@rename 5 6 || goto DirectoryError
@rename 4 5 || goto DirectoryError
@rename 3 4 || goto DirectoryError
@rename 2 3 || goto DirectoryError
@rename 1 2 || goto DirectoryError
@mkdir 1
---- now "folder 1" will be empty, ready to receive backup image
by anonymous - 2008-05-07 15:11
This is good piece of information.

I Changed my code to do the backup dynamically. I need to copy the files that were created today. I am pasting the my code below.

@ECHO ON
set year=%date:~10,4%
set month=%date:~4,2%
set day=%date:~7,2%
set yyyymmdd=%date:~10,4%-%date:~4,2%-%date:~7,2%
set today= %date:~4,2%-%date:~7,2%-%date:~10,4%

set copyfrom="C:\Documents and settings\My Documents\Notes"
set Drive="C:\Documents and settings\My Documents\Backup"
set folder=%yyyymmdd%
set backupcmd=xcopy
echo...........Backing up the files...........

%backupcmd% %copyfrom% %Drive%\%folder% /D:%today%
pause
pause

echo ....... backed up files.........

If I run this I am getting an error " Invalid Number of parameters".

I don't know what I am doing wrong. Any help would be appreciated
by Stanly - 2008-05-22 02:34
Thank you for the codes.
I have made some changes and used "move" command instead of "Xcopy"

@echo Registry backup of %computername%' is in progress.........
@echo off
set temp=c:\windows\temp
regedit /e "%temp%\%computername%.reg"
cls
@echo ----Registry Backup Completed and copying to destination folder........
@echo off
move %temp%\%computername%.reg
cls
@echo %computername%.reg file copied to destination.
@pause
by babyraj - 2008-06-30 12:04
Hi all ,

I have question .Is there any way to copy the changed files to different folder?

I mean

xcopy /d /e /y c:\folder1 d:\folder1 this will copy only the changed files to d:\fplder1 its OK.My question is how can we copy only chnaged files to d:\folder2.


Thanks.
by John - 2008-08-31 14:19
Hi I'm trying to write my first batch file. I'm using the code Given in this thread. My problem is on the first command is being done. the My documents folder is being backed up and then the file stops executing.

If I remove the commands to back up My documents then the favorites folder is backed up but it will not continue after that.

Any help getting all the commands to execute would be greatly appreciated.

Thanks
J
by shinobi - 2008-09-02 00:07
can someone help me? i want to back-up "My Documents" from another pc using batch files???? thanks in advance for the effort and help...
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