how to backup using batch files

Upload: sajith-c-vijayan

Post on 04-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 How to Backup Using Batch Files

    1/8

    How to Backup using Batch Files2004.12.10 13:03 EST by Philip

    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 upcomparatively easy with a simple click, by creating and running a batch file. That file can be executedmanually 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 goodlearning experience by example. You can simply copy the text below, and paste it into Notepad. Createa 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%\OutlookExpress"

    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 hiddenfiles.

    In the above file, all lines that begin with "::" are comments. The "set drive=" and "set backupcmd=" nearthe 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 outputthe line of text to the screen, and the lines beginning with %backupcmd% are the actual commands to

    mailto:[email protected]://%20what%20is%20regedit%20/?http://%20what%20is%20regedit%20/?mailto:[email protected]://%20what%20is%20regedit%20/?
  • 7/29/2019 How to Backup Using Batch Files

    2/8

    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 LANwith computername "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 toexecute it.

    Using the Current Date

    Sometimes it is useful to create folders with the date incorporated in the folder name. Here is how to setthe 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 boththe current date and time to the minute, separated by underscores. There is an extra step that cleans uppossible 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 definesthe 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 asa subdirectory. The third variable, "backupcmd" defines our backup command with the appropriate

    command line switches we want to use.

    @echo off

    http://%20what%20is%20lan%20/?http://%20what%20is%20lan%20/?http://%20what%20is%20lan%20/?
  • 7/29/2019 How to Backup Using Batch Files

    3/8

    :: variablesset drive=D:\Backupset 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] isthe 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 arenewer, speeding up subsequent backups. Alternatively you can add a line to delete the %folder% directoryprior 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, asapplicable. It is especially useful if you're backing up full, multiple user profiles and overwriting themperiodically. Since temporary files and cookies change, your backed up directories will keep increasing withunnecessary files. To remedy this, the following code can be added to the backup script, or to a separatebatch file. It will automatically search all subdirectories for "cookies", "temp" and "history", and thenremove those directories:

    :: change to the destination drive firstG::: your parent backup directorydrive=G:\Backup

    echo ### Searching for files to clean up...

    cd %drive%dir /s/b/ad \cookies > %drive%\cleanup.txtdir /s/b/ad \temp > %drive%\cleanup.txtdir /s/b/ad \history > %drive%\cleanup.txt

    echo ### Deleting cookies, temp files and history from backup dirfor /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 forfiles to delete. Any sub-folders that contain "cookies", "temp", or "history" will be deletedautomatically. You can test to see what will be deleted by commenting out the "for /f ....." line (justadd :: to the beginning of the line, or delete it from the batch file and add it again later). If that line is notpresent, 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 backupbatch file, you may want to remove the "@pause" line at the end of the backup portion, so everything canexecute without user interacion.

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

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

  • 7/29/2019 How to Backup Using Batch Files

    4/8

    Notes:

    Any batch file can be interupted with CTRL+C or CTRL+Break if needed. They can also be pausedwith the Pause/Break key.

    Instead of backing up My Documents, Favorites, Outlook and Outlook Express files separately, youcan combine it all into one line for the current user: %backupcmd% "%USERPROFILE%""%drive%\%UserName% - profile" . The only disadvantage being that it would savetemporary IE files as well (however the default location of those can be changed, or youcan 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.

    User Reviews/Comments: rate:

    avg:

    byDavid - 2006.02.10 14:48

    For the UK people who may stumble upon this...check out the date and time line which will capture the

    date and time... if today was 23/06/2006 and 19:30, the variable dateNtime would be 23-06-2006_19-30

    Hope this saves someone some time!! The code is below

    @echo off:: variables

    set drive=M:\mybackup

    SET dateNtime="%date:~0,2%-%date:~3,2%-%date:~6,6%_%time:~0,2%-%time:~3,2%"set backupcmd=xcopy /s /c /d /e /h /i /r /k /y

    echo ### Backing up your Sites directory...%backupcmd% "C:\Program Files\Sites" "%drive%\%dateNtime%"

    echo Backup Complete - Your Backup is located at %drive%

    @pause

    by Grant - 2006.02.20 21:45

    Can some tell how I could backup multiple PC (say 40) using the backup script without writing 400+ linesof code. Is there another script I can attach this to and run a loop program. Sorry I am not a program

    writer

    by philip - 2006.02.22 16:25

    You only need one additonal line for each LAN client/directory, not 10. For example, to backup theadministrator profile on 3 remote machines named COMP1, COMP2, and COMP2, you'd need somethinglike:

    @echo off:: variablesset drive=g:\Backupset backupcmd=xcopy /s /c /d /e /h /i /r /k /y

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

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

    http://www.speedguide.net/faq_in_q.php?category=89&qid=171http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=4http://forums.speedguide.net/member.php?u=4http://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/faq_in_q.php?category=89&qid=171http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=4
  • 7/29/2019 How to Backup Using Batch Files

    5/8

    echo Backup Complete!@pause

    And so on, for each client you want to backup. In other words, you do need to add one line of code foreach directory you're backing up (it includes all subdirectories as well), I am not sure how you can furthersimplify that.

    by Al - 2006.02.28 13:54

    I am trying this cool script but I get an error message "Invalid Number of Parameters" when running thescript. Only on the lines that include %USERPROFILE% in them. For example%backupcmd% "%USERPROFILE%\My Documents" "%drive%\My Documents"

    Any suggestions???

    Thanks in advance

    byandrew - 2006.03.01 14:02

    Big sigh of relief. This is so easy. I don't have to figure out Retrospect, which imho is just appalling. Thankyou thank you.

    by zorak1083 - 2006.04.10 11:16

    David,

    If i want to rename a folder when it's backed up deppending on the date, for example i have a folder withfiles that are populating every day in C:\pictures and i want to make a backup of it every to D:\Backup butchange the folder name to "pictures_dd_mm_yyyy" what do i have to do? Rename the folder beforebacking up or during the backup procedure?The main problem of this procedure is how to avoid overwriting every time the new folder to the backupdestination to the old folder.How the system will be able to identify the current dd_mm_yyyy?Can you send me the code for this batch?

    Thanx for your time

    by anonymous - 2006.04.24 12:47

    Is there a command I can use to search the c:\ drive till it finds a file, then back it up?.........

    thanks

    by anonymous - 2006.06.01 08:57

    I've got the backup working but want to use it as a daily backup of one drive to another. What do I needto do to replace the previous day's backup?

    by Philip - 2006.06.01 09:49

    The xcopy "/d" command-line parameter specifies that the command is to copy all source files that arenewer than existing destination files. Using this option allows you to update the backup directory only withfiles that have changed since last time you ran it (rather than copying all files). You should still end upwith identical directories/files after execuring the batch file, while saving time for consecutive backups.

    I hope this helps. Please direct any further questions to our forums. Thanks.

    http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=179485http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=4http://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=179485http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=4
  • 7/29/2019 How to Backup Using Batch Files

    6/8

    byRavi - 2006.06.24 04:09

    HI,

    I was in bad need of creating a batch file for backup and the script you have given in the website hasreally satisfied my requirement. Thanks for the help. Wishing you ALL THE BEST!!!

    Regards,

    Ravi Verma Vegesna

    by denis2006 - 2006.07.12 16:25

    how do I make a batch file to run weekly that copies the source directory (which is the 'c' drive in mycase) a\to the backup directory (which is the 'd' drive for me) in windows?

    by MyK - 2006.08.09 09:13

    Hi guys, i'm having trouble figuring out how to create one script that copies different files at specified timeintervals?

    I have an application that outputs files everyhour with a different file name and i need to be able to copy

    each at a specified time interval.

    by loganj - 2007.01.09 13:17

    I am using this batch with a few changes. It is working great. I am having to manually go in and deleteolder backups though. How do I get it to only keep 7 days of backups? always overwriting the oldest date?thanks

    byPhil - 2007.01.18 11:21

    Your code works great! Buttt.... When I put the batch file in the Scheduled Tasks and try to get it to run itBombs. I look in the logfile and it says it ran successfully. I been trying to search the problem and the onlything I come up with is someone posted about having problems with drive letters in the batch file not

    working and having to put in \\server\folder. I tryed but to no avail. Help!! Thanks in advance.

    by captainkaos - 2007.01.31 01:24

    i HAVE TRIED MODING THE CODE WITH NO HOPE OF IT

    i want to back up a network drive drive letter(x) with a folder name ( ma) X:\ma

    to D:\macode @echo off

    :: variablesset drive=x:\Backup

    set backupcmd=xcopy /s /c /d /e /h /i /r /y%backupcmd% "x:\ma" "%drive%\ d:\ma"

    echo Backup Complete!@pause

    ????? where have i gone wrong Capt Kaos Australia

    http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=188176http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=198946http://forums.speedguide.net/member.php?u=198946http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=200080http://forums.speedguide.net/member.php?u=200080http://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=188176http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=198946http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=200080
  • 7/29/2019 How to Backup Using Batch Files

    7/8

    by eurofins - 2007.02.01 15:55

    The batch file works great and has saved me a lot of time, but what about a code that will automaticallycancel the script should a network drive not be detected? It would be great for those remote customersnot to get the error when a mapped drive is not there.

    Any help on this would be great.Thanks

    by Philip - 2007.02.01 20:50

    captainhaos, just use this:

    @echo off:: variablesset backupcmd=xcopy /s /c /d /e /h /i /r /y%backupcmd% "x:\ma d:\ma"echo Backup Complete!@pause

    byDoron - 2007.02.06 15:40

    Hi Philip,

    This is great, just what i searched for, thank you.Is it possible (WinNT) to create a directory, in which its name is made of the PC host name and date, andif not, how can i prompt the user to insert it manually?

    Thanks in advance,

    Doron

    byXplosiV - 2007.02.28 01:03

    Very good and simple batch file, I edited the original to suit and added the UK date part but that didnt givefolders by date. Other than that, All works great. Thanx loads.

    byEddieduce - 2007.04.20 16:26

    How can I add a couple of lines to make my backup automatically save to one of the following foldersdepending on the day of the week?Today is i.e. FridaySave to:MondayTuesdayWednesdayThursday------>Friday

    You have to process the returned %Date% as it is not directly suitable to be used as a folder/file

    name.

    On Computing Net there is a lot of examples about your issue: try XP, Programming, DOS

    Forum.

    hi,

    u just cut paste the following code, then it will really work out.

    http://forums.speedguide.net/member.php?u=200151http://forums.speedguide.net/member.php?u=4http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=203822http://forums.speedguide.net/member.php?u=203822http://forums.speedguide.net/member.php?u=203822http://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://www.speedguide.net/comment_add.php?id=1547&type=articlehttp://forums.speedguide.net/member.php?u=200151http://forums.speedguide.net/member.php?u=4http://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://www.speedguide.net/read_articles.php?id=1547#comments%23commentshttp://forums.speedguide.net/member.php?u=203822
  • 7/29/2019 How to Backup Using Batch Files

    8/8

    @echo off

    cd c:\temp

    set folder=%date:~10,4%%date:~7,2%%date:~4,2%

    mkdir %folder%

    move c:\temp c:\%folder%

    byeramesh

    thank you very much for the reply. that works very well. it creates a folder, 20043011 for todays

    instance. one more quick question, if i change line 3 to look like this:

    set folder=%date:~10,4%%date:~4,2%%date:~7,2%

    instead of this:

    set folder=%date:~10,4%%date:~7,2%%date:~4,2%

    will todays folder now look like 20041130?