-1

I have two parameters. It was suggested that this is a duplicate question, but I want to specify a minimum age AND a minimum number of files to be kept. I'm not sure how to combine those parameters.

I have a batch file which includes this code:

 @echo off

set "backupDir=[BACKUP DIR PATH HERE]"

copy /Y "[PATH OF FILE TO BE COPIED]" "[PATH WHERE BACKUP IS SAVED]"

for /f "skip=4 delims=" %%a in ('dir "%backupDir%\" /b /a-d /o:-d') do del "%backupDir%\%%a"

It creates a backup of a database and deletes everything except the four most recent instances. What I want is to make sure that if the batch file is run more than once in a day, I don't end up deleting the old files and end up with four copies of what would essentially be the same backup.

How can I specify that the file must be at least "N" days old before deletion?

It might be better to have something that limits the file from running again if it hasn't been at least 24 hours since the last time. But I don't know how to do that either.

Ben H.
  • 102
  • 7
  • 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) – aschipfl Aug 20 '18 at 08:38
  • I looked at that one and was unsure how to add it to my script. I want to only keep four, as long as the four are from different days. – Ben H. Aug 20 '18 at 08:49

2 Answers2

1

If I understand correctly, you want to delete all but the newest four backups, but only if they have got a minimum age (or, more precisely, if they have been modified earlier than a certain number of days ago).
The following code does exactly that:

pushd "%backupDir%" || exit 1
rem // Iterate files but skip the four ones that have been modified most recently:
for /F "skip=4 delims=" %%F in ('dir /B /A:-D /O:-D "*.*"') do (
    rem // Verify whether the last modification date is at least seven days ago:
    for /F "delims=" %%I in ('
        2^> nul forfiles /P "%%~dpF." /M "%%~nxF" /D -7 /C "cmd /C echo @path"
    ') do (
        ECHO del "%%I"
    )
)
popd

Remove the upper-case ECHO after having verified the correct output.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
0

use forfiles

forfiles /P "%backupDir%" /M *.* /D -10 /C "cmd /C echo @path"

You can change the number of days where -10 is.

Change echo to del only when you are 100% sure it echo's the correct files you want to delete.

You can be more specific with your file types by replacing *.* with your file extension or actual file name. i.e *.MYD or backup_db* etc.

For more info run forfiles /? from cmd.exe

To add the line above to your script, simply replace this line:

for /f "skip=4 delims=" %%a in ('dir "%backupDir%\" /b /a-d /o:-d') do del "%backupDir%\%%a"

with the forfiles line.

Gerhard
  • 22,678
  • 7
  • 27
  • 43