Windows Active Directory Snapshots

Set scheduled task to run daily and call this maintainSnapshots.bat file:
------------------------------
@echo off

REM Logs Location (Used for manage retention). The folder have to contain only the text files of this batch.
set mypath=C:\ADSnapshotLogs\
if not exist %mypath% mkdir %mypath%

REM Setup of the retention of snapshots in seconds (31 Days = 2678400)
set myretention=2678400

REM Generation of a Linux TimeStamp for the naming of log files
REM (Time in seconds since 1970-01-01 00:00:00 ex : 205329600 for Sun Jul 4 12:00:00 1976 GMT)
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do (set %%x)
set /a z=(14-100%Month%%%100)/12, y=10000%Year%%%10000-z
set /a mydate=y*365+y/4-y/100+y/400+(153*(100%Month%%%100+12*z-3)+2)/5+Day-719469
set /a mydate=mydate*86400+100%Hour%%%100*3600+100%Minute%%%100*60+100%Second%%%100

REM Creation of the snapshot
ntdsutil snapshot "activate instance ntds" create quit quit > %mypath%%mydate%.txt

REM Get the ID of the Snapshot and save it into the log file
for /f "tokens=1,2,3,4,5 delims= " %%a in ('findstr /i /c:"{" "%mypath%%mydate%.txt"') do @echo %%c > %mypath%%mydate%.txt

REM Removing old snapshot
echo Removing old snapshot
for /f "tokens=1,2 delims=." %%a in ('dir %mypath% /b') do call :CalcRetension %%a
goto end
:CalcRetension
set val=%1
set /a result=%mydate%-%myretention%
IF %val% LSS %result% (
for /f "tokens=1,* delims= " %%a in ('findstr /i /c:"{" "%mypath%%val%.txt"') do call :removeSnapshot %%a %val%
)
goto end
:removeSnapshot
set guid=%1
set filename=%2
ntdsutil snapshot "delete %guid%" quit quit
del /S "%mypath%%filename%.txt"
goto end
:End

Leave a Reply

Your email address will not be published. Required fields are marked *