MS-DOS: BackUp Script Example

DOS backup example:

  • Put the files in a new directory and cleanup the 11th oldest
  • Using EnableDelayedExpansion the variables are preserved
@echo off
setLocal EnableDelayedExpansion

SET DESTINATION_DIR="D:\TEST_DESTINATION"
SET SOURCE_DIR="C:\TEST_SOURCE"


REM MAKE A NEW DIRECTORY TO PUT THE FILES INSIDE:
REM ---------------------------------------------

SET NEW_BACKUP_DIR=BACKUP_DB_%DATE:~4,2%_%DATE:~7,2%_%DATE:~10%_%TIME:~0,2%_%TIME:~3,2%
MKDIR %DESTINATION_DIR%\old\%NEW_BACKUP_DIR%


REM LOOP THROUGH FILES AND PUT THEM IN THE DIRECTORY CREATED ABOVE:
REM ---------------------------------------------------------------

FOR /f %%a IN ('DIR %DESTINATION_DIR% /B /A:-D /T:C') DO (
COPY %DESTINATION_DIR%\%%a %DESTINATION_DIR%\old\%NEW_BACKUP_DIR%

REM COPY %DESTINATION_DIR%\%%a %DESTINATION_DIR%\old\%%a__%DATE:~4,2%_%DATE:~7,2%_%DATE:~10%_%TIME:~0,2%_%TIME:~3,2%
)

REM COPY THE FRESH FILES INTO THE DESTINATION DIRECTORY FROM THE SOURCE DIRECTORY:
REM ------------------------------------------------------------------------------

COPY /Y %SOURCE_DIR%\* %DESTINATION_DIR%\


CD %DESTINATION_DIR%\OLD
SET /a the_counter=0


REM LOOP THROUGH THE DIRECTORIES, IF THEY ARE MORE THAN 10 THEN REMOVE DIRECTORY
REM ----------------------------------------------------------------------------

FOR /f %%a IN ('DIR %DESTINATION_DIR%\OLD /B /A:D /T:C /O:-D') DO (
SET /a the_counter=!the_counter!+1
IF !the_counter! GTR 10 RMDIR %%a /S /Q
)
endLocal

Leave a Reply