Skip to main content

How to Create a Basic Backup Script in a Batch Script

One of the most valuable and fundamental tasks you can automate with a batch script is creating a backup. Manually copying folders is tedious and prone to human error. A well-written script can ensure that your important files, like documents, project files, or photos, are consistently and correctly backed up to another location, such as an external hard drive or a network share.

This guide will teach you how to create a simple but powerful backup script using the modern, built-in Robocopy command. You will learn the essential switches to create a "mirror" of your source directory, how to log the results, and how to make your script reusable and easy to configure.

Choosing the Right Tool: Why Robocopy?

While COPY and XCOPY can copy files, Robocopy ("Robust File Copy") is the professional and definitive tool for any serious backup script.

Key Advantages of Robocopy:

  • It is efficient. It can check timestamps and file sizes and will only copy files that are new or have changed, making subsequent backups much faster.
  • It is resilient. It has built-in logic to automatically retry copying files that are temporarily locked by another program.
  • It provides detailed logging. You can easily create a log file to review what was copied and see any errors that occurred.
  • It can mirror directories. It can intelligently delete files from the backup destination if they have been deleted from the source, keeping the two locations in perfect sync.

The Core Command: Robocopy with the /MIR Switch

The heart of a synchronization-style backup is the /MIR (MIRror) switch. This tells Robocopy to make the destination directory an exact replica of the source.

Syntax: ROBOCOPY "Source_Folder" "Destination_Folder" /MIR

  • Source_Folder: The folder you want to back up.
  • Destination_Folder: The location where the backup will be stored.
  • /MIR: This powerful switch does three things:
    1. Copies all new or updated files and folders from the source to the destination.
    2. Copies all subdirectories, even empty ones.
    3. Deletes any files in the destination that no longer exist in the source. This is a critical feature that keeps your backup from getting cluttered with old, deleted files.
warning

WARNING: The /MIR switch is destructive to the destination. If you accidentally reverse your source and destination paths, it could wipe out your original data. Always double-check your paths.

Example: A Basic Mirroring Backup Script

This script is a simple, effective way to mirror a user's Documents folder to a backup drive.

@ECHO OFF
TITLE My Document Backup

SET "Source=%USERPROFILE%\Documents"
SET "Destination=E:\Backups\Documents"

ECHO --- Starting Document Backup ---
ECHO Source: %Source%
ECHO Destination: %Destination%
ECHO.

ECHO Synchronizing folders... Please wait.
ROBOCOPY "%Source%" "%Destination%" /MIR

ECHO.
ECHO --- Backup Complete ---
ECHO Exit Code: %ERRORLEVEL%
ECHO (Note: 0 or 1 are success codes for Robocopy)
ECHO.
PAUSE

How the Mirroring Script Works

When you run the script, Robocopy compares the source and destination.

  • On the first run, it will copy everything.
  • On subsequent runs, it will only copy files that you have added or changed since the last backup.
  • If you deleted a file from your Documents, it will also be deleted from E:\Backups\Documents.

Key Robocopy Parameters for Backups

To make your backup script more robust, you should add a few more switches.

SwitchDescriptionRecommended Value
/R:<N>Retry count for locked files./R:2 (Try twice)
/W:<N>Wait time in seconds between retries./W:5 (Wait 5 seconds)
/LOG:<File>Creates a LOG file, overwriting it each time./LOG:backup.log
/NPNo Progress. Hides the xx% completion counter for cleaner logs./NP
/EFSRAWCopies encrypted files in EFS RAW mode. Essential for backing up encrypted data./EFSRAW
/XF <File>eXcludes Files matching a pattern./XF "thumbs.db" "*.tmp"

Common Pitfalls and How to Solve Them

  • Accidentally Deleting Backup Files: As warned, the /MIR switch will delete files. If your backup drive is disconnected and Robocopy sees the destination as "empty," it could wipe the contents if the destination path still resolves (this is rare, but possible).

    • Solution: Always use IF EXIST to verify that your source directory exists before you run the Robocopy command.
  • Locked Files: The script might fail if it tries to copy a file that is currently open (like an Outlook .pst file).

    • Solution: Use the /R and /W switches to give Robocopy a chance to wait and retry the copy.
  • Interpreting the Exit Code: A Robocopy exit code of 1 is a success (meaning files were copied). A script that checks for IF %ERRORLEVEL% NEQ 0 will incorrectly report a failure.

    • Solution: The correct check is IF %ERRORLEVEL% LSS 8 (Less than 8). Any exit code from 0-7 indicates that the job completed without fatal errors.

A More Robust and Reusable Backup Script

This script incorporates best practices, including configuration variables at the top, path validation, logging, and smart error checking.

@ECHO OFF
SETLOCAL
TITLE Robust Backup Script

REM --- ===================== ---
REM --- CONFIGURATION ---
REM --- ===================== ---
SET "SourceDir=C:\Users\Admin\Documents\Projects"
SET "BackupDir=E:\Backups\Projects_Mirror"
SET "LogFile=%~dp0BackupLog.txt"
SET "Exclusions=/XF *.tmp *.bak ~$*"

ECHO --- Starting Robocopy Backup ---
ECHO Source: "%SourceDir%"
ECHO Destination: "%BackupDir%"
ECHO.

REM --- Safety Check: Ensure the source directory exists before proceeding ---
IF NOT EXIST "%SourceDir%\" (
ECHO [ERROR] Source directory not found. Backup aborted.
ECHO %DATE% %TIME% - ERROR: Source directory not found. >> "%LogFile%"
PAUSE
GOTO :EOF
)
MKDIR "%BackupDir%" 2>NUL

ECHO Synchronizing... This may take a while.
robocopy "%SourceDir%" "%BackupDir%" /MIR /EFSRAW %Exclusions% /R:2 /W:5 /NP /LOG+:"%LogFile%"

ECHO.
ECHO --- Operation Complete ---
IF %ERRORLEVEL% LSS 8 (
ECHO [SUCCESS] Backup completed without fatal errors.
) ELSE (
ECHO [FAILURE] Robocopy reported a serious error. Please check the log.
)
ECHO Log file is at: "%LogFile%"
PAUSE
ENDLOCAL

Conclusion

Robocopy is the definitive tool for creating powerful, reliable backup scripts in a Windows environment.

For a robust backup solution:

  • Use Robocopy "Source" "Destination" /MIR to create an exact mirror of your data.
  • Always double-check your paths and use an IF EXIST check on your source directory as a safety measure.
  • Add switches like /R:2 /W:5 to handle locked files gracefully.
  • Log your results (/LOG+) so you have a record of what happened.
  • Check the exit code correctly: IF %ERRORLEVEL% LSS 8 is the standard check for success.