Windows Batch Script To Backup Data

As I have briefly mentioned in my previous posts, for my day job I am the primary technical resource for a small business and as a “side gig” I manage web servers for hosting companies. One of the great benefits to this is I have become quite adept at developing command line scripts, or “batch” scripts.

One of the most common, and well suited, applications for a command line script is data backup. Command line scripts can be automated to run at any time without any human interaction and are only limited by… well, nothing.

Why Command Line Scripts?

Having experience with both commercial and free backup programs, I always find command line scripts to be, by far, the most effective tool for the job. Here are a few reasons why:

  • Native Commands: What better way to backup data than by using the functions made available through the program which creates the data. Whether this is the operating system itself via a simple file copy command or a database command to produce a restorable binary file, the source program knows how best to back itself up.
  • Ultimate Control: Since a command line script follows a simple step-by-step procedure, you know exactly what is happening and can easily modify the behavior.
  • Fast: Since everything is a native command, nothing is subject to interpretation. Again, you are using commands provided by the program itself, so overhead is kept to a minimum.
  • Powerful: I have yet to see a backup task which cannot be accomplished through a command line script… and I have done some funky stuff. Albeit, some research and “trial and error” may be required, unless you need something incredibly unique, typically the built in functions and features of the scripting language you are using is more than sufficient.
  • Free and Flexible: Obviously, a command line script does not cost anything (outside the time to develop it), so the emphasis I want to make is command line scripts can be copied to and implemented on other systems and quickly adapted with little to no time or cost. Compare this to the cost of purchasing licenses for backup software on several servers and/or desktop machines.

A Quick Overview Of The Backup Batch Script

Since a lot of people do not have the need/time/desire to learn command line scripting, it is considered somewhat of a “black art”. So to demonstrate the power of the command line, I am providing a simple Windows batch script to backup your important data. This configurable and customizable script does not
require any knowledge (or willingness to learn) of the Windows batch scripting language.

What the backup script does:

  1. Creates full or daily incremental (see below for a definition) backups of files and folders you specify in a separate configuration text file (see below).
    • When a folder is provided, that folder and all sub-folders are backed up.
    • When a file is provided, just that file is backed up.
  2. Compresses (zips) the backed up files. After all files to be backed up are copied, they are compressed to save space. 7-Zip is required to be installed on your system for this to work.
  3. Dates the compressed file and moves it to a storage location. After the backup files are compressed, the resulting archive is given a file name according to the current date and then moved to a configured storage location, such as an external drive or network location.
  4. Cleans up after itself. After all tasks are completed, the batch script cleans up all the temporary files it created.

Requirements:

Windows 2000/XP/2003/Vista,
7-Zip (it’s free).

Configuration file:

The configuration file is simply a text file which contains files and folders to backup, entered one backup item per line. This file must be named “BackupConfig.txt” and be located in the same folder as the backup script. Here is an example of a BackupConfig.txt file (note, the first line is always ignored):

# Enter file and folder names, one per line.
C:\Documents and Settings\Jason Faulkner\Desktop C:\Documents and Settings\Jason Faulkner\My Documents\Important Files C:\Scripts\BackupScript.bat

The example above would backup the Windows user Jason Faulkner’s desktop (and all folders on the desktop), the folder called “Important Files” inside of My Documents (and all folders inside “Important Files”) and the file “BackupScript.bat” inside the C:\Scripts directory.

Types of backups:

  • Full backup: A complete copy of all files and folders (including sub-folders) are included in the backup.
  • Incremental backup: When a folder is provided, only files created or modified on the current date are
    backed up. When a file is provided, it is always backed up, regardless of when it was modified.

The Data Backup Windows Batch Script

I want to emphasize this script is very basic, as all it does is create backups by a utilizing a simple file copy. There are some configuration options you can set:

  • The backup storage location where the resulting compressed backup files are stored.
  • The day of the week the full backup is run (any other day would run an incremental backup).
  • Location of where 7-Zip is installed on your computer. The script is automatically set to look in the default location.

If you have any suggestions or feature requests, please comment below. I would really love to do a follow up article to this post which features an updated script based on reader input.

If you need instructions on how to “use” this script or set up a scheduled task, take a look at the links below the script source.

Without further ado, here it is:
Note: Since the quotes do no display correctly below (and as a result can mess up the script), I have included a plain text link below the script which you can use to get an accurate source to copy from.

@ECHO OFF

REM BackupScript
REM Version 1.01, Updated: 2008-05-21
REM By Jason Faulkner (articles[-at-]132solutions.com)

REM Performs full or incremental backups of folders and files configured by the user.

REM Usage---
REM   > BackupScript

SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

REM ---Configuration Options---

REM Folder location where you want to store the resulting backup archive.
REM This folder must exist. Do not put a '\' on the end, this will be added automatically.
REM You can enter a local path, an external drive letter (ex. F:) or a network location (ex. \\server\backups)
SET BackupStorage=C:\Backup

REM Which day of the week do you want to perform a full backup on?
REM Enter one of the following: Sun, Mon, Tue, Wed, Thu, Fri, Sat, *
REM Any day of the week other than the one specified below will run an incremental backup.
REM If you enter '*', a full backup will be run every time.
SET FullBackupDay=*

REM Location where 7-Zip is installed on your computer.
REM The default is in a folder, '7-Zip' in your Program Files directory.
SET InstallLocationOf7Zip=%ProgramFiles%\7-Zip

REM +-----------------------------------------------------------------------+
REM | Do not change anything below here unless you know what you are doing. |
REM +-----------------------------------------------------------------------+

REM Usage variables.
SET exe7Zip=%InstallLocationOf7Zip%\7z.exe
SET dirTempBackup=%TEMP%\backup
SET filBackupConfig=BackupConfig.txt

REM Validation.
IF NOT EXIST %filBackupConfig% (
  ECHO No configuration file found, missing: %filBackupConfig%
  GOTO End
)
IF NOT EXIST "%exe7Zip%" (
  ECHO 7-Zip is not installed in the location: %dir7Zip%
  ECHO Please update the directory where 7-Zip is installed.
  GOTO End
)

REM Backup variables.
FOR /f "tokens=1,2,3,4 delims=/ " %%a IN ('date /t') DO (
  SET DayOfWeek=%%a
  SET NowDate=%%d-%%b-%%c
  SET FileDate=%%b-%%c-%%d
)

IF {%FullBackupDay%}=={*} SET FullBackupDay=%DayOfWeek%
IF /i {%FullBackupDay%}=={%DayOfWeek%} (
  SET txtBackup=Full
  SET swXCopy=/e
) ELSE (
  SET txtBackup=Incremental
  SET swXCopy=/s /d:%FileDate%
)

ECHO Starting to copy files.
IF NOT EXIST "%dirTempBackup%" MKDIR "%dirTempBackup%"
FOR /f "skip=1 tokens=*" %%A IN (%filBackupConfig%) DO (
  SET Current=%%~A
  IF NOT EXIST "!Current!" (
    ECHO ERROR! Not found: !Current!
  ) ELSE (
    ECHO Copying: !Current!
    SET Destination=%dirTempBackup%\!Current:~0,1!%%~pnxA
    REM Determine if the entry is a file or directory.
    IF "%%~xA"=="" (
      REM Directory.
      XCOPY "!Current!" "!Destination!" /v /c /i /g /h /q /r /y %swXCopy%
    ) ELSE (
      REM File.
      COPY /v /y "!Current!" "!Destination!"
    )
  )
)
ECHO Done copying files.
ECHO.

SET BackupFileDestination=%BackupStorage%\Backup_%FileDate%_%txtBackup%.zip

REM If the backup file exists, remove it in favor of the new file.
IF EXIST "%BackupFileDestination%" DEL /f /q "%BackupFileDestination%"

ECHO Compressing backed up files. (New window)
REM Compress files using 7-Zip in a lower priority process.
START "Compressing Backup. DO NOT CLOSE" /belownormal /wait "%exe7Zip%" a -tzip -r -mx5 "%BackupFileDestination%" "%dirTempBackup%\"
ECHO Done compressing backed up files.
ECHO.

ECHO Cleaning up.
IF EXIST "%dirTempBackup%" RMDIR /s /q "%dirTempBackup%"
ECHO.

:End
ECHO Finished.
ECHO.

ENDLOCAL

Plain text source is available here: Jason Faulkner’s Backup Script

If you need help getting started with implementing this script, here are a couple of links to help you out:

This is the same script I use to backup my computer daily (with a couple of modifications of course), so I know it works very well. I hope you find it useful.

Enjoy.

Free eBook!

Like what you read?

If so, please join over 28,000 people who receive our exclusive weekly newsletter and computer tips, and get FREE COPIES of 5 eBooks we created, as our gift to you for subscribing. Just enter your name and email below:

Post A Comment Using Facebook

  • djemmers

    hi , after a quick test this looks like it is working great,

    did you ever made the follow up article like you said?

    one thing isn’t clear to me:
    “Incremental backup: When a folder is provided, only files created or modified on the current date are”
    So let’s say this happends
    day 1: full backup
    day 2: no changes , incremental backup
    day 3: changes, incremental backup
    day 4: changes, but no backup is made (for wathever reason)
    day 5: changes, incremental backup

    if I understand it,
    the changes from day 4 are not backed up? because incremental is only created or modifiede ON THE CURRENT DATE ?

    • Jason Faulkner

      Correct. I am using the XCOPY tool which only supports copying files for the current day.
      I may get around to revising this, but I don’t have any plans too at the moment.

      • Mark

        Use xcopy /d with no argument to copy all updated files.

  • http://www.jimward.us Jim Ward

    I hope you backup script solves the Vista & Windows 7 file attribute hassle that seems related to DRM. I can copy anything to any other folder or partition on my laptop but have problems dragging & dropping to the NAS on my wifi network.

    • http://www.pcrecoveryllc.com Michael Theriot

      I wrote my own batch file that initializes a VPN connection offsite, then backs up company data offsite. Then disconnects. I think I will modify my script to compress files as you did, however, I would prefer to compress my folders FIRST, then transmit the data of course. Thanks for sharing the info on 7-zip. I’ll be looking at it, as well as any alternatives.

  • eugene

    Hi,

    I’m implement daily backup which start at 2am daily.

    How do store the filename using dd/mm/yy format

    example
    Backup_20-07-09_Full.zip

    instead the follwing format which i dun want.

    Backup_07-2009-_Full.zip
    Any idea?
    Thanks

    • Jason Faulkner

      Change the lines that reads:
      SET FileDate=%%b-%%c-%%d
      to
      SET FileDate=%%c-%%b-%%d

  • eugene

    Hi Jason Faulkner,

    The filename became Backup_2009-07-_Full.zip,instead my expectation which is Backup_2009-07-dd_Full.zip
    still missing the day format, any idea?Do i miss out any thing?

  • Mike

    How do i get the script to only back up the previous 7 days files. I want it to look at the date modify date

  • Pan

    I tried your script and it works great for directories however once I try to copy a file or add a file in the list, it shows the message as follows:

    The system cannot find the path specified.
    0 file(s) copied.

    I tried to debug it and could see that the destination path is showing as follows:

    C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\backup\C\USB\backup\Test\PHPTest

    The same path is for directory copying however it works perfectly but not while copying the single file.

    The code which needs review is as follows:


    FOR /f “skip=1 tokens=*” %%A IN (%filBackupConfig%) DO (
    SET Current=%%~A
    IF NOT EXIST “!Current!” (
    ECHO ERROR! Not found: !Current!
    ) ELSE (
    ECHO Copying: !Current!
    SET Destination=%dirTempBackup%\!Current:~0,1!%%~pnxA
    REM Determine if the entry is a file or directory.
    IF “%%~xA”==”" (
    REM Directory.
    XCOPY “!Current!” “!Destination!” /v /c /i /g /h /q /r /y %swXCopy%
    echo !Current!
    echo seperator
    echo !Destination!
    echo dirend
    ) ELSE (
    REM File.

    COPY /v /y “!Current!” “!Destination!”
    echo !Current!
    echo seperator
    echo !Destination!
    )
    )
    )

    Any idea?

    • Paul

      Thanks for this script Jason.
      It seems COPY does not create the destination path for the file. Tried using XCOPY but it prompts since it doesn’t know if it needs to create a file or folder. I pipe the ‘f’ in since we know it is a file. It seems to work but there might be a better way?
      COPY /v /y “!Current!” “!Destination!” —> echo ‘f’ | XCOPY /v /y “!Current!” “!Destination!”

      • http://signedesign.nl Willem

        I’m on a Dutch version of Windows 7 and although i don’t know a thing about dos commands, I notice that the input flag is language specific.
        The best way to figure out the required input in your language is to run the adjusted batch script from an (elevated) command prompt and see what pops up.

        The original line in the script is:
        COPY /v /y "!Current!" "!Destination!"

        Paul suggests:
        echo 'f' | XCOPY /v /y "!Current!" "!Destination!"

        In my case (in Dutch) this becomes:
        ECHO B | XCOPY /v /y "!Current!" "!Destination!"

        Note that i’ve left out the single quotes around the input “B”. The script will run with the quotes (sort of) but they’re superfluous.

        (Please ignore any code-tags with the examples)

  • sune

    im trying to use that script but only does an empty zip file…

  • http://ds-forums.info Kyle

    Hey this script works amazing! I was wondering tho, it does save it as a *.zip file, I was wondering if we can change the compression to “best” and have it create a *.7z file instead, is this possible to tune it up like that?

    My output is 1.6gb and I wanted to compress it to make it smaller, and create it in a *.7z. Is that possible? Thanks so much!

  • Nick

    I love this script, any plans to make modifications to allow FTP upload for offsite backups?

    • Jason Faulker

      I’m doing this in a couple of scripts I have on our servers, it is not very difficult.

      Basically you use the FTP command in your script (this is a tool built into Windows) and then pass it a file which has the FTP server name, password and then the subsequent transfer commands each on a single line.

      There are plenty of pages out there which explain how to use this, so google help regarding the Windows FTP command and the command line and you can see some examples.

  • HoHum

    Thank you for this script. It has enhanced my knowledge of batch scripting. I have an issue:

    For some strange reason, there must be an existing environmental variable because my backups always include Picasa3 folders; namely: “\CDPrep” and “\Picasa2AlbumsTemp”. The strangeness of this is that the BackupConfig.txt only contains ONE directory to backup. Any thoughts?

  • SenHu

    I enjoyed reading your discussion on “Why Command Line Scripts?”. How very appropriate. Have you considered using biterscripting ( http://www.biterscripting.com ) on windows instead of batch ? It has much better parsing, comparing, catalogging and monitoring capabilities.

  • Jennifer

    I can’t seem to get the script working for me. I’m using XP and in the config file I used the following:
    # backup files
    “\\Fs-data\data2\OVI\Safety Management\BRU referentielijst.xls”
    “\\Fs-data\data2\OVI\Safety Management\[INC] Incidenten\[DOS] Dossiers\INC-DOS-0041 hazard log.xls”
    It doesn’t matter if I use quotation marks, the files just won’t backup. I can get the file to work when putting in:
    \\Fs-data\data2\OVI\Safety Management, however that backups the entire subfolder structure as well, while I only want to backup these 2 files.
    Can somebody help me?

    • Jason Faulkner

      Try replacing this line:
      COPY /v /y “!Current!” “!Destination!”

      with this:
      XCOPY “!Current!” “!Destination!” /v

  • Jennifer

    Hi Jason, thanks for the tip, but I still get an empty zip-folder. Any other ideas?

  • Shan

    Please check your BackupConfig.txt file
    the first line is always ignored .

  • Jennifer

    still, I can’t imagine something wrong with the following:

    # backup files
    \\Fs-data\data2\OVI\Safety Management\BRU referentielijst.xls
    \\Fs-data\data2\OVI\Safety Management\[INC] Incidenten\[DOS] Dossiers\INC-DOS-0041 hazard log.xls

  • Mick

    Thanks for posting this script for us to use! I have been using it since the summer of 2009 and it’s worked great. As a tip for anyone who cares I cloned the script and use multiple instances of it for several different directories that I want to backup. That way, I can schedule them up to run whenever I feel like it. I feel so much better now that I’ve been able to back up my music.

  • dvdljns

    Can you do a follow up but instead of using 7zip use mkisofs to build spanning iso files cd. using cds to store backups is the way to go.

  • Denis

    my ‘date’ command returns only date. there is no day of week
    I have Windows Server 2003
    also tried on Windows 7. same result.

    • Jason Faulkner

      Change this:
      REM Backup variables.
      FOR /f “tokens=1,2,3,4 delims=/ ” %%a IN (‘date /t’) DO (
      SET DayOfWeek=%%a
      SET NowDate=%%d-%%b-%%c
      SET FileDate=%%b-%%c-%%d
      )

      To this:
      REM Backup variables.
      FOR /f “tokens=1,2,3 delims=/ ” %%a IN (‘date /t’) DO (
      SET DayOfWeek=%FullBackupDay%
      SET NowDate=%%c-%%a-%%b
      SET FileDate=%%a-%%b-%%c
      )

      This will cause the script to run a full backup every time, but since you do not have the day of week, there is no way to avoid it.

      • Denis

        Found a workaround:
        Echo.|Command /C Date|Find “Current”
        but need to be modified.

  • Frank

    The script creates an emtpy backup file for me as well with win 2003 server. I found out that it ignores the first line in the config file.

    Config file:
    c:\test1 <– no backup
    c:\test2 <– backup
    c:\test3 <– backup

    The first line may be empty.
    Hope this helps and thanks for your script.

  • Scott

    I have tried to run the script on a 2000 box — verified that the config file is there and after the script runs it terminates immediately indicating that the config file is missing.

    Any ideas?

    Thanks,

    • Jason Faulkner

      Try changing the line which reads:

      IF NOT EXIST %filBackupConfig% (

      to

      IF NOT EXIST “%filBackupConfig%” (

  • Mike

    Hi To All,

    Im a newbie in netbackup system. Would like to ask some assistance about scripting. We have an existing Replication Manager (RM) that is doing the cloning of disk. and when the cloning is finish we then perform a backup. But we usualy encounter an error. It s because that the cloning is not yet finish and the backup schedule starts already. My boss ask me to create a script that will call to backup the disk after it finish the cloning. I see that we can put the script in the RM system to call it after if finish the cloning. My problem is that scheduling on backup.

    we have Daily backup, Weekly backup and every 28 of the month fullbackup.

    for daily = 1 week retention
    for weekly = 2 weeks retention
    for 28th of the month = 1 month retention.

    How to create a script that will check if is Monday, Tuesday, Wednesday, Thursday, Friday, Saturday = Daily; Sunday will be Weekly and every 28th of the month is Monthly backup.

    Please help me if you have a script that I can use for this setup.

    Thank you very much,

    Regards,
    Mike
    email :netbackup_newbie@yahoo.com.sg

  • Dawie

    Loving the script. Got around a problem with incremental backups by changing the below:

    SET FileDate=%%b-%%c-%%d
    to
    SET FileDate=%%b-%%c-2010

    For some reason it does not want to include the year but the above works.

    I however cannot use variables like %username% or %appdata% in the “BackupConfig.txt” file.

    Any idea why not?

    • Jason Faulkner

      The BackupConfig.txt file reads the data in as literal text. It will not process environment variables.

  • Hassan Bintook

    I want to do monthly backup and delete the files

    Also the output file should be like xxxxxx_Mar2010.rar

    Thanx

  • ken

    I use this scripts, i think is pretty good. It get the job done.
    Now, is there away to Exclude a files or folders?

    I have few Vmware folder(BIG size) and few temp folder, which i dont want to back it up.

    TY
    k

  • ismashkhy

    Hi, I’m a newbie in scripting, can this be possible?

    source folder
    \Folder1\sample.txt

    destination backup folder
    \Folder1\sample.txt

    each time the backup is initiated, I only need the added or modified files are the only one that is copied onto the backup destination…

    is this possible?, I don’t need any date or what so ever at this time of trying scripting for the first time?…

    can anyone give me template script of what I want to do?..

    the file to be copied is as it is…copied as original not compressed in zip or rar…

    thanks in advance

What’s Your Preference?

Daily Alerts

Each day we send out a quick email to thousands of PCMECH readers to notify them of new posts. This email is just a short, plain email with titles and links to our latest posts. You can unsubscribe from this service at any time.

You can subscribe to it by leaving your email address in the following field and confirming your subscription when you get an email asking you to do so.

Enter your email address for
Daily Updates:

Weekly Newsletter

Running for over 6 years, the PCMECH weekly newsletter helps you keep tabs on the world of tech. Each issue includes news bits, an article, an exclusive rant as well as a download of the week. This newsletter is subscribed to by over 28,000 readers (many who also subscribe to the other option) - come join the community!

To subscribe to this weekly newsletter simply add your email address to the following field and then follow the confirmation prompts. You will be able to unsubscribe at any time.

Enter your email address for
Free Weekly Newsletter: