2

I have a line of code I use for backing up client SQL databases that will trim the number of stored backed up files to 7 days to prevent it growing out of control over time.

However I have noticed a problem. The client is running the script very in frequently so when they do it deletes everything apart the new file run at the time. I could tell them do it everyday but you know how it is, it wont happen and I need to mitigate against this.

I would like it so that the code runs and doesn't delete anything older than 7 days but keeps the most recent 7 days worth of files if that makes sense?

forfiles -p "Cache" -s -m *.* -d -7 -c "cmd /c del @path"

Is there a way to alter this so it reads the date of the files and always keeps the most recent 7 days worth, no matter when the script is run. Rather than just seeing everything in here (at the point of execution) is older than 7 days and delete it all?

Tika9o9
  • 405
  • 4
  • 22
  • 1
    [this](https://stackoverflow.com/a/45432074/2152082) should be easy to adapt. (it deletes the *newest* files, keeping n files, as you need to delete the *oldest*, but replacing `/od` with `o-d` solves that) – Stephan Aug 07 '17 at 12:10
  • 2
    Possible duplicate of [Batch file to delete files older than N days](https://stackoverflow.com/questions/51054/batch-file-to-delete-files-older-than-n-days) –  Aug 07 '17 at 12:17
  • thanks I managed to get something sorted with Stephan link. Do I need edit OP at all to show the line? – Tika9o9 Aug 07 '17 at 13:47
  • @LotPings: no, Tika don't want "keep last seven days" but "keep last seven files". Tika9o9: no, don't put your answer into the question. You may answer your question instead in the "Your Answer" box below. – Stephan Aug 08 '17 at 05:31

1 Answers1

1
for /f "skip=14 delims=" %%a in ('dir /a-d /o-d /b /s "C:\Path_To_Folder"') do DEL "%%a"

change skip=14 to whatever number of recent files you want to keep.

Tika9o9
  • 405
  • 4
  • 22