How to Synchronize Two Folders with Robocopy in Batch Script
Keeping a backup or a secondary location perfectly in sync with a source directory is a critical task in data management. This process, often called "mirroring," ensures that the destination is an exact replica of the source, any files added, changed, or deleted in the source are reflected in the destination. The definitive, professional-grade tool for this job in Windows is Robocopy (Robust File Copy).
This guide will teach you how to use Robocopy's powerful mirroring capabilities to synchronize two folders. You will learn the essential /MIR switch, understand its destructive power, and see a practical example of a reliable backup script.
The Core Command: Robocopy
Robocopy is the standard Windows utility for all serious file and folder copying operations. It is vastly superior to XCOPY and COPY, offering better reliability, logging, automatic retries for locked files, and the ability to perform complex synchronization tasks.
The basic syntax is:
ROBOCOPY "Source_Folder" "Destination_Folder" [options]
The Mirroring Switch: /MIR
The most powerful switch for synchronization is /MIR (MIRror). When you use /MIR, you are telling Robocopy to make the destination look exactly like the source.
This single switch is a convenient shortcut for three other switches combined:
/E: Copies all subdirectories, Even empty ones./COPYALL: Copies ALL file information (Data, Attributes, Timestamps, Security, Owner, Auditing info)./PURGE: This is the key. Deletes files and directories in the destination that no longer exist in the source.
Critical Warning: Understanding What /MIR Does
The /PURGE behavior of the /MIR switch is what makes it so powerful, but also so dangerous.
If a file exists in the destination but not in the source, /MIR will permanently delete it.
Consider this scenario:
- Source:
C:\MyData(containsfile_A.txt) - Destination:
D:\Backup(containsfile_A.txtandfile_B.txt)
If you run ROBOCOPY C:\MyData D:\Backup /MIR, Robocopy will look at the destination, see that file_B.txt does not exist in the source, and it will delete file_B.txt from the backup.
Always double-check your source and destination paths. If you reverse them by mistake, you could wipe out your source data.
Basic Example: Mirroring a Project Folder
Let's synchronize a working project folder to a backup location.
@ECHO OFF
SET "SOURCE=C:\Users\Admin\Documents\CurrentProject"
SET "DESTINATION=D:\Backups\CurrentProject_Backup"
ECHO Synchronizing project folder to backup location...
ROBOCOPY "%SOURCE%" "%DESTINATION%" /MIR
What happens:
- Any new or updated files in
CurrentProjectwill be copied to the backup. - Any files that you deleted from
CurrentProjectwill now be deleted from the backup. - The result is that the backup folder becomes an identical snapshot of the project folder.
Key Robocopy Parameters for Synchronization
While /MIR is the main switch, a few others are essential for creating robust scripts:
/R:<N>: Specifies the number of Retries on failed copies (e.g., for locked files). A good default is/R:2./W:<N>: Specifies the Wait time in seconds between retries. A good default is/W:5./LOG:<File>: Creates a LOG file, overwriting it each time./LOG+:<File>: Appends to an existing log file./NP: No Progress. Hides the percentage counter for cleaner log files./TEE: Outputs to the console window (To Editor) as well as the log file.
Common Pitfalls and How to Solve Them
The Dangers of an Incorrect Path
As mentioned, a typo in your source or destination path can be catastrophic. If Robocopy can't find the source, it might think the source is "empty," and if you use /MIR, it will proceed to wipe your destination.
Solution: Always use IF EXIST to validate your paths before running a destructive command like Robocopy /MIR.
IF NOT EXIST "%SOURCE%\" (
ECHO [CRITICAL ERROR] Source path not found. Aborting.
GOTO :EOF
)
IF NOT EXIST "%DESTINATION%\" (
ECHO [WARNING] Destination path not found. Creating it...
MKDIR "%DESTINATION%"
)
ROBOCOPY "%SOURCE%" "%DESTINATION%" /MIR
Handling Locked Files (/R and /W)
If your script tries to copy a file that is currently open (e.g., an Outlook .pst file or a database file), the copy will fail. By default, Robocopy will retry a whopping one million times!
Solution: Always specify a reasonable retry count and wait time using /R and /W. A command like /R:2 /W:5 tells it to try twice, with a 5-second wait, before giving up on a locked file and moving on.
Interpreting Robocopy's Exit Codes
Robocopy has unique exit codes. An exit code of 0 means no files were copied and no errors occurred. An exit code of 1 means files were successfully copied. Both are considered success.
Solution: A simple rule for checking the exit code (%ERRORLEVEL%) is:
- Less than 8: Success (files may or may not have been copied, but no fatal errors occurred).
- 8 or higher: Failure (a serious error occurred, like an invalid path or access denied).
Practical Example: A Robust Daily Backup Script
This script combines all the best practices into a reliable daily backup utility.
@ECHO OFF
SETLOCAL
REM --- Configuration ---
SET "SOURCE_DIR=C:\Users\Admin\Documents"
SET "BACKUP_DIR=E:\Backups\Documents"
SET "LOG_FILE=E:\Backups\backup_log.txt"
ECHO --- Robocopy Mirroring Backup Script ---
ECHO.
ECHO Source: %SOURCE_DIR%
ECHO Backup: %BACKUP_DIR%
ECHO.
REM --- Safety Check: Ensure source exists ---
IF NOT EXIST "%SOURCE_DIR%\" (
ECHO [ERROR] Source directory not found. Backup aborted.
GOTO :End
)
MKDIR "%BACKUP_DIR%" 2>NUL
ECHO Starting synchronization...
REM --- The Robocopy Command ---
ROBOCOPY "%SOURCE_DIR%" "%BACKUP_DIR%" /MIR /R:2 /W:5 /NP /LOG+:"%LOG_FILE%" /TEE
REM --- Check the result ---
IF %ERRORLEVEL% LSS 8 (
ECHO [SUCCESS] Synchronization completed without fatal errors.
) ELSE (
ECHO [FAILURE] Robocopy reported a serious error. Check the log.
)
ECHO Log file is available at: "%LOG_FILE%"
:End
ENDLOCAL
Conclusion
Robocopy with the /MIR switch is the definitive tool for synchronizing folders in a Windows environment. It is fast, reliable, and provides the control needed for professional-grade backup and mirroring scripts.
For safe and effective synchronization:
- Use
ROBOCOPY "Source" "Destination" /MIRas the core command. - Be extremely careful with your source and destination paths, as
/MIRwill delete files in the destination. - Always use safety checks (
IF EXIST) in your scripts to validate paths before running. - Include
/Rand/Wto gracefully handle locked files. - Check the
%ERRORLEVEL%after the command, treating any value less than 8 as success.