Pages

Monday, October 26, 2015

Windows Batch Script for Incremental Backup



Recently I faced with the problem when I wanted to do a backup of some directory just by one click. I didn't want to rename or change something manually each time I need to do a backup. All I want is just copy the content of one folder to some destination many times by one single mouse click. 

This means that each time I run a backup I want my script to check if there already exist some previous backup folder and if yes then to increment it's name and actually perform the backup. Thus if I will run the script 5 times then the destination directory will look like this:

incremental-backup-folders-structure

Well I must confess it was not easy to find a solution for this relatively simple task. Therefore I decided to put a result of my research here in order to do someone's life easier.
Here is a Windows batch script that will do incremental backup for you:

@echo off

:: copy content of this folder
set source=c:\temp\test\1
:: to this destination
set dest_path=c:\temp\test\2\

:: this command works for UNC paths. 'cd' works only on local paths.
pushd %dest_path%

:: this block handles incrimentation. 
:: for the first time this block will create "Backup1" directory
:: otherwise it will create directory with incremented name
setlocal enableDelayedExpansion
set "dest_folder_name=Backup"
set "n=0"
for /f "delims=" %%F in (
 '2^>nul dir /b /ad "%dest_folder_name%*."^|findstr /xri "%dest_folder_name%[0-9]*"'
) do (
 set "name=%%F"
 set "name=!name:*%dest_folder_name%=!"
 if !name! gtr !n! set "n=!name!"
)
set /a n+=1
set final_destination="%dest_path%%dest_folder_name%%n%"
md %final_destination%
:: ---
robocopy %source% %final_destination% /E /R:3 /W:10 /FFT /NP /NDL
popd

@echo on

Create a batch execution file with bat extension, copy paste this script into it, change source and destination paths and run it.
Enjoy!

No comments:

Post a Comment