Solved

Batch file to count directories and keep 5 recent ones

Posted on 2010-08-17
26
980 Views
Last Modified: 2012-06-27
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.
0
Comment
Question by:falimorad
  • 8
  • 7
  • 7
  • +3
26 Comments
 

Expert Comment

by:tstrausb
ID: 33456697
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
 
LVL 23

Expert Comment

by:DanCh99
ID: 33458023
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
 
LVL 23

Expert Comment

by:DanCh99
ID: 33458135
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
 
LVL 16

Expert Comment

by:t0t0
ID: 33458409
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
 
LVL 16

Expert Comment

by:t0t0
ID: 33458473
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
 
LVL 51

Expert Comment

by:Bill Prew
ID: 33460486
==> 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
 
LVL 16

Expert Comment

by:t0t0
ID: 33460701
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
 
LVL 16

Expert Comment

by:t0t0
ID: 33460723
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
 
LVL 2

Expert Comment

by:misterlupo
ID: 33462392
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
 
LVL 16

Expert Comment

by:t0t0
ID: 33462441
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
 
LVL 16

Assisted Solution

by:t0t0
t0t0 earned 150 total points
ID: 33462467
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
 

Author Comment

by:falimorad
ID: 33464285
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
 
LVL 2

Expert Comment

by:misterlupo
ID: 33464323
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:falimorad
ID: 33464355
It still has more than 5 directories.  I ran it but it didnt delete anything.
0
 
LVL 2

Expert Comment

by:misterlupo
ID: 33464410
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
 

Author Comment

by:falimorad
ID: 33464451
Yes to both your questions
0
 
LVL 2

Expert Comment

by:misterlupo
ID: 33464611
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
 

Author Comment

by:falimorad
ID: 33464699
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
 
LVL 2

Expert Comment

by:misterlupo
ID: 33464746
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
 

Author Comment

by:falimorad
ID: 33464810
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
 
LVL 2

Expert Comment

by:misterlupo
ID: 33464840
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
 

Author Comment

by:falimorad
ID: 33464924
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
 

Author Comment

by:falimorad
ID: 33464943
Yours and t0t0 both worked, I just had to put the script in the directory
0
 
LVL 2

Accepted Solution

by:
misterlupo earned 350 total points
ID: 33464992
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
 

Author Comment

by:falimorad
ID: 33465663
Works like a charm
0
 
LVL 16

Expert Comment

by:t0t0
ID: 33467715
Thank you.

Sorry I was away during the discussion above.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

I have published numerous articles here at Experts Exchange that present programs/scripts written in a language called AutoHotkey. Each of those articles has a brief paragraph describing where to download the product and how to install it. I have al…
Today, still in the boom of Apple, PC's and products, nearly 50% of the computer users use Windows as graphical operating systems. If you are among those users who love windows, but are grappling to keep the system's hard drive optimized, then you s…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now