![]() |
How to Backup using Batch Files2004-12-10 (updated: 2020-09-30) by PhilipTags: 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:
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):
Backing up Other Directories and networked PCs You can backup other directories by simply creating more alike lines:
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:
Here is another example, backing up the Administrator Profile on a machine on the LAN with computer name "Lianli":
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):
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:
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.
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:
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:
See Also: How to backup using Batch Files in Windows 10 (using Robocopy) Notes:
User Reviews/Comments:
rate:
avg:
![]() ![]() ![]() ![]() ![]()
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
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
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%" ...
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)
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
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.
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
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!
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?
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
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
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.
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
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
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! |