I have a file .bat that do a backup but i want to do another file .bat that remove the oldest files. Someone can help me?
set dia=%DATE:~0,2%
echo %dia%
if exist f:\exist.txt goto OK
echo KKKKKKKKKK
pause
exit
:OK
md f:\backup
md f:\backup\%dia%
xcopy d:\dat\*.* f:\backup\%dia%\*.* /s /c /h /r /e /y /j
echo TODO OK
pause
Read carefully please! The script has a safeguard echo
in the rmdir
line. Do not remove this until you are 100% sure the script does what you want.
@echo off
for /f "tokens=2 delims=.=" %%i in ('wmic os get localdatetime /value') do set result=%%i
set "mydate=%result:~0,8%"
robocopy "d:\dat" "f:\backup\%mydate%" /MIR /Z
for /f "skip=4 delims=" %%a in ('dir /b /ad /o-d "f:\backup\"') do echo rmdir /S/Q "%%~fa"
pause
So the script will create a folder for each date yyyymmmdd
each time you run it, if the folder already exists i.e you ran the backup twice in one day, it will simply update the files and not recreate any folders if they exist.
The second for loop you have to be carefull of. it will sort the folders by decending date, i.e the latest created folders will be listed first. So you will see here I have skip=4
meaning it will skip the first 4 latest folders, and delete the rest. So if you want to keep two latest backups, then do skip=2
etc.
to amend the date to yyyymm
only, change to set "mydate=%result:~0,6%"
. You get the idea.