Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my .bat script doesn't delete the files when the total count reaches 8 in the folder?


setlocal EnableDelayedExpansion

pushd C:\backups
set top=7
set filespec=*.bak
set counter=0

for /f "delims=" %%f in ('dir /b %filespec%') do (
    set /a counter+=1
    if !counter! GTR %top% del /q "%%f"
)

I have .bak files, if the number of backup files gets more than 7 i.e. 8 then delete the oldest one.

for example

 1. bak1.bak      10:01 am
 2. bak2.bak      10:02 am
 3. bak3.bak      10:03 am
 4. bak4.bak      10:04 am
 5. bak5.bak      10:05 am
 6. bak6.bak      10:06 am
 7. bak7.bak      10:07 am
 8. bak8.bak      10:08 am

now, the script shall delete then bak1.bak which was taken at 10:01 hence oldest.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Making it

 1. bak2.bak      10:02 am
 2. bak3.bak      10:03 am
 3. bak4.bak      10:04 am
 4. bak5.bak      10:05 am
 5. bak6.bak      10:06 am
 6. bak7.bak      10:07 am
 7. bak8.bak      10:08 am

so if again a file is added i.e.

bak9.bak 10:09

then delete the oldest one i.e. bak2.bak

I wrote the script to but it doesn’t exactly work that way. What it does is that it only keeps the top 7 records even if the number of files are more than 8 e.g. rightnow i have 13 files and if i run it it will keep only top 7 and rest 6 would be deleted but this needs to happen only if the number of files gets 8 and hence deleting the oldest one hence making them 7 again.

>Solution :

Right now, you aren’t listing the files by age, you’re listing them alphabetically by filename. In order to list the files by age, you need to use the /o:-d option of dir in order to sort them from newest to oldest.

@echo off
setlocal EnableDelayedExpansion

pushd "C:\backups"
set "top=7"
set "filespec=*.bak"
set "counter=0"

for /f "delims=" %%f in ('dir /b /o:-d %filespec%') do (
    set /a counter+=1
    if !counter! GTR %top% del /q "%%~f"
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading