-1

I have written a Windows scheduler that takes the backup of a folder in a particular location. The folder names are appended with the current time-stamp.

echo Starting Backup of File System
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (
    set dt=%%c-%%a-%%b
)
For /f "tokens=1-4 delims=:." %%a in ('echo %time%') do (
   set tm=%%a%%b%%c%%d
)
set bkupfoldername=UPLOADS_BACKUP_%1%dt%_%tm%

xcopy D:\Source > D:\Destination\%bkupfoldername% /Y /E /H /I

echo Backup has been completed.

I want to run another scheduler job, that should keep the latest 30 folders in the Destination folder and delete the rest.

I'm new to this. What do you think must be working?

Balaji Vignesh
  • 446
  • 1
  • 7
  • 19
  • 2
    What is the output of your `DATE /T` command and what does your `TIME` variable resolve to? So basically what I am asking is are you naming them as `YYYYMMDDhhmm`. Regardless of that, we could assume that your folders are never edited after the fact and just use this: `FOR /F "skip=30 delims=" %%G IN ('dir /AD /B /O-D uploads_backup_*') do rd /s /q "%%~G"` This code essentially skips the newest 30 folders based on their last modified date and deletes the rest of them. – Squashman Oct 25 '17 at 13:55
  • See chapter 2 in answer on [Versioning up existing files using batch](https://stackoverflow.com/a/46857785/3074564) for a better solution getting date and time in a specific format and read the answer on [Batch job to delete folder older than 7 days on Windows 7](https://stackoverflow.com/a/36785448/3074564) explaining in detail how the __FOR__ command line as posted by [Squashman](https://stackoverflow.com/users/1417694/squashman) works. – Mofi Oct 25 '17 at 17:13

1 Answers1

2

Use dir /o-d to sort in reverse time order:

for /f "skip=30 delims=" %%d in ('dir /ad /b /o-d /tc D:\Destination\UPLOADS_BACKUP_*') do (
    rd /s /q "D:\Destination\%%d"
)
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
  • Read my comment above. – Squashman Oct 25 '17 at 14:06
  • `SKIP=30`. I won't post it as answer until I can guarantee that his backups are never edited after they have been backed up. If someone goes in and edits a file in the directory the modified time becomes newer and then it is not keeping the newest 30 folders based on the date and time in the actual folder name. – Squashman Oct 25 '17 at 14:10
  • @Squashman your comment gives a better answer than mine. You are rightly concerned about the possibility of the folder being updated after creation, so I've just added the `/tc` option to the `dir` command to make it use the creation time. – DodgyCodeException Oct 25 '17 at 14:13
  • You are not going to use the `SKIP` option? – Squashman Oct 25 '17 at 14:17
  • @Squashman yes the skip option is a good idea, which I didn't want to steal from you, but since you insist, I'll do it ;-) – DodgyCodeException Oct 25 '17 at 14:27
  • Thank you Squashman and DodgyCodeException. That works perfect! – Balaji Vignesh Oct 26 '17 at 05:15