WillM
WillM

Reputation: 11

Windows script to remove more than x files from directories & sub dirs

I am looking to write a script that deletes more than 'n' files (likely 5 versions) starting with the oldest first, keeping the latest 5 files in hundreds of directories. These directories are all nested under one root folder.

These are copies of backup files that are created during a nightly process and, for reasons I will not go into, I have no current control over the backup system to tell it to only keep 5 copies, or I would have done it that way... I cannot just use anything that is based on date alone because in some cases the last 10 versions are the last 10 days but in others the backups are weekly, monthly or even ad-hoc, so the dates go back 10 weeks/months on a set day or whatever... I have tried all kinds of scripting myself but cannot seen to get this right...

I found one that works well for a single directory but I have not been able to make this go down through the sub-dirs and work properly.

So, if I run this:

@echo off &setlocal set folder=d:\test\test1

pushd "%folder%"

for /f "skip=5 tokens=*" %%i in ('dir /a:-d-s /b /o:-d') do del "%%i"

popd


It goes to the 'd:\test\test1' directory and leaves the latest 5 files and removes the rest. It works no matter how many files are in that directory.

So now, what I really want, is to have this walk from 'd:\test' down the directories below and remove all but 5 file versions in all those directories. I have tried variations with a '/s' in the dir command, but have not hit on one that quite does it...

Been playing with this for several days with no success... Anyone have any ideas I am open to anything... Thanks!

Upvotes: 1

Views: 568

Answers (1)

Kalpesh Patel
Kalpesh Patel

Reputation: 31

FOR /R "d:\test\test1\" %%G in (.) DO (
Pushd %%G

Echo now in %%G

for /f "skip=5 tokens=*" %%i in ('dir /a:-d-s /b /o:-d') do echo "%%i"

Popd )

Upvotes: 3

Related Questions