Batch file to count directories and keep 5 recent ones

Hey guys, I have a batch file that backs up files everyday and stores them in a directory that is which has the date and time in this format dd-mm-yyyy_hour-minute and the time is military time.  I want to create a batch file that would go count the number of directories and once it reaches 5 directories, it will delete the oldest directory.
falimoradAsked:
Who is Participating?
 
misterlupoConnect With a Mentor Commented:
good that it finally worked. save the attached code into a deleteoldfolders.cmd file and you may run it from any local directory.

@echo off
set backupfolder=c:\backup
for /f "tokens=* skip=5" %%a in ('dir /ad /b /o-d "%backupfolder%"') do rd /s /q "%backupfolder%\%%a"

Open in new window

0
 
tstrausbCommented:
I had this same issue. Below is a sample batch file; it's arguably not very efficient but it will work. You'll have to enter some specific information; ***path*** should be replaced with the path to the directory containing the backup directories. Save the below as a bat file and place it in the "c:\" directory. You can schedule this to run with windows scheduled tasks or on startup, etc.

setlocal enabledelayedexpansion
:getto5
dir /od ***path***>c:\dirlist.txt
for /f "tokens=1*" %%a in (c:\dirlist.txt) do (
      set DIRCOUNT=%%a
      )
if !DIRCOUNT! GEQ 8 (
            set DIRCOUNTER=1
            for /f "skip=5 tokens=5*" %%x in (c:\dirlist.txt) do (
                  set OLDESTDIR!DIRCOUNTER!=%%x
                  set /a DIRCOUNTER=!DIRCOUNTER!+1
                  )
            rmdir /s /q ***path***\!OLDESTDIR1!
            set /a DIRCOUNT=!DIRCOUNT!-1
            goto :getto5
            )
endlocal
0
 
Danny ChildIT ManagerCommented:
Another potentially useful tool would be the FORFILES resource kit tool. It's been around for years, and I think the most recent version is from 2003, but it still works on all current OSs.

It can delete files by age in days, which may be helpful.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
Danny ChildIT ManagerCommented:
Examples:
http://www.lifeasbob.com/2009/06/26/ForFiles.aspx

And when you download forfiles, make sure you get the most recent version - 46k in size, if I recall...

0
 
t0t0Commented:
The following one line should do the trick quite nicely:

AS A SINGLE COMMAND:

   @for /f "tokens=*" %a in ('dir /ad /b /o-d^|more +5') do @del /f /s /q "%~dpnxa"



AS BATCH FILE CODE

   @echo off
   for /f "tokens=*" %%a in ('dir /ad /b /o-d^|more +5') do del /f /s /q "%%~dpnxa"
0
 
t0t0Commented:
Oh, don't forget to drop the batch file into the folder containing your backup folders OR better still, specify the target folder in the code like this:

If your backup folder is say, E:\BACKUP\ then you'll need to add that to the code like this:

   for /f "tokens=*" %%a in ('dir /ad /b /o-d E:\BACKUP\^|more +5') do del /f /s /q "%%~dpnxa"

0
 
Bill PrewCommented:
==> t0t0

I like your approach, as long as the poster agrees that using the date last modified date of the directory is the same as using the name of the directory, which is a date stamp. I would think that's a valid assumption, I wouldn't expect any additional writes to the directory after the backup.

In your solution, wouldn't "%%fa" be an easier way to reference the directory to process?  I don't think DIR can ever add quotes to it's listing so no need for the tilde, and the F modifier is the same as DPNX.

Also, should the command to use be RD rather than DEL, to remove the entire directory?

Other than that, I like it, nice and simple.

~bp
0
 
t0t0Commented:
prew...

You're lookin' sharp again...

The %%fa is a good suggestion (I just like to individually specify each component however, you're absolutely right).

The tilde-thing is part of 'dpnx' as in %%~dpnxa or, as you've pointed out, %%~fa.

I'll go along with the RD-thing especially as we can add the '/S' and '/Q' command line options.

Yep, KISS

As suggested, I'll reflect those changes right away:

   @echo off
   for /f "tokens=*" %%a in ('dir /ad /b /o-d^|more +5') do rmdir /s /q "%%~fa"


Thank you.
0
 
t0t0Commented:
falimorad

No need to muck about with dates and times etc... Please see the modified code below.

   @echo off
   for /f "tokens=*" %%a in ('dir /ad /b /o-d^|more +5') do rd /s /q "%%~fa"

This will leave the 5 most recent folders (as created bo DOS) intact while removing any others (along with their contents).
0
 
misterlupoCommented:
just to add my 2 cent, the "for" command can be configured to skip the first x lines, so no need to pipe it in to more and the potential pitfall to forget to escape the pipe symbol.

for /f "tokens=* skip=5" %%a in ('dir /ad /b /o-d') do rd /s /q "%%~fa"
0
 
t0t0Commented:
misterlupo

Great point... It just gets better and better...

Looking at the code, I really don't think it can be improved any further.... The only omission is the patth to the source folder.


    for /f "tokens=* skip=5" %%a in ('dir /ad /b /o-d') do rd /s /q "%%~fa"


Surely, that MUST be the one!
0
 
t0t0Connect With a Mentor Commented:
Oops! I meant...


    for /f "tokens=* skip=5" %%a in ('dir /ad /b /o-d "c:\backup\"') do rd /s /q "%%~fa"


where c:\backup is where the backup folders are located. Obviously, this will differ on the author's PC.
 
0
 
falimoradAuthor Commented:
For some reason it is saying The system cannot find the file specified, is it because we are using the /f switch? I double checked the folder name, everything is correct
0
 
misterlupoCommented:
single quoted strings areusually treated as a commands. Try to use "usebackq"

for /f "tokens=* skip=5 usebackq" %%a in ('dir /ad /b /o-d "c:\backup\"') do rd /s /q "%%~fa"

0
 
falimoradAuthor Commented:
It still has more than 5 directories.  I ran it but it didnt delete anything.
0
 
misterlupoCommented:
does the user you run this command under has the rights to delete them?
does a rd /s /q "path_to_a_directory" deletes it?
0
 
falimoradAuthor Commented:
Yes to both your questions
0
 
misterlupoCommented:
Could you run the below to see if it creates the correct commands?

for /f "tokens=* skip=5 usebackq" %%a in ('dir /ad /b /o-d "c:\backup\"') do @echo rd /s /q "%%~fa"

0
 
falimoradAuthor Commented:
I put that in the batch file, and ran, but still nothing.  It seems to run but does do that job.  You can even test it out.  the directory c:\backup has 6 directories and it remains six when running the script
0
 
misterlupoCommented:
if you run it straight in a command prompt, replace the %% with %. the double %% are meant to be in a .cmd script. Try this

for /f "tokens=* skip=5" %a in ('dir /ad /b /o-d "c:\backup\"') do @echo rd /s /q "%~fa"
0
 
falimoradAuthor Commented:
hmmmmm.  It does show that it is deleting the oldest directory, but when I go to check, it still didn't delete it.  I also tried rmdir, and it does show that the command is being applied to the directory but it just doesnt delete it. I also went and manually applied the command which worked.
0
 
misterlupoCommented:
the previous command was just to test if it runs the right stuff, please remove the @echo and it will delete the dirs.

for /f "tokens=* skip=5" %a in ('dir /ad /b /o-d "c:\backup\"') do rd /s /q "%~fa"
0
 
falimoradAuthor Commented:
It worked but I had to go into c"\backup and do it while I was in there which is fine but it worked.
0
 
falimoradAuthor Commented:
Yours and t0t0 both worked, I just had to put the script in the directory
0
 
falimoradAuthor Commented:
Works like a charm
0
 
t0t0Commented:
Thank you.

Sorry I was away during the discussion above.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.