We help IT Professionals succeed at work.

batch file to delete files in a directory

Dan
Dan asked
on
I'm looking for a very simple batch file that will delete files in a folder.
here's some requirements.
1. to be able to specify how many days I want to keep files in the directory (newest files of course by modify date)
2. the batch file should not delete itself after the x days has been reached (only to delete the files specified)
3. to be able to specify whether it deletes everything in the specified directory, or by specifying, for example, *.bak, *.xml, etc..
4. Can it have the ability to check for subfolders and delete files there as well?
Comment
Watch Question

CERTIFIED EXPERT

Commented:
forfiles -p "c:\folder\subfolder" -s -m *.* -d  <days> -c "cmd /c del @PATH"

where days should be a negative number ..

so older than 10 days would be
forfiles -p "c:\folder\subfolder" -s -m *.* -d  -10 -c "cmd /c del @PATH"

DanNetwork Engineer

Author

Commented:
So I just enter -10 for hte script to keep the 10 newest files, right?
Ok, the path is self explanatory, but is there a way for me to specify which file types to delete only?
Also, will the bath file delete itself after 10 days, as the modify date will be older then 10 days?
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
Is this different then to the requirements here?
http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/MS_DOS/Q_27417162.html
Steve

Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
Do you want 10 newest files.... or files from last 10 days.   Different things potentially unless only fixed one file per day.  e.g. if your backup did not run for 5 days then you would only have 5 backups.  If you pick last 10 files then it will keep 10 days worth.

We looked before at subdirs and you wanted different criteria for different dirs?

Batch file / VBS will not delete itself if it doesn't hit the criteria for the files, or more easily, is put outside of the directory structure being aged.

The VBS below similar to I have before will delete all files over 10 days old from c:\somedir and all subdirs.  It will also remove any folders under that dir that were created before the cut off date and are empty.  That can be removed if needed.

It then does c:\someotherdir for over 5 days old
and c:\someotherdiragain for over 1 month old

Please check on test dir first of course if using as have added changes here without testing at the mo.

Steve
' Call initial folder to delete and it will work down subdirs
' By running recursively through subdirs after doing files
' in each dir. Second parameter is date of last files to leave
' Anything older will go.
' Stephen Knight July 2009

Dim deletionDate
Dim fso
Dim oFile
Dim oFolder

Set fso = CreateObject("Scripting.FileSystemObject")

DeleteFiles "c:\somedir",DateAdd("d", -10, Date),".bak"
DeleteFiles "c:\someotherdir",DateAdd("d", -5, Date),".bak"
DeleteFiles "c:\someotherdiragain",DateAdd("m", -1, Date),".bak"


msgbox "Deleting older than " & DateAdd("m", -1, Date)

Set oFolder = Nothing
Set oFile = Nothing
Set fso = Nothing

Function DeleteFiles(foldername,cutoffdate,extension)
Set oFolder = fso.GetFolder(foldername)

For Each oFile in oFolder.Files
If ofile.DateCreated < cutoffDate AND right(lcase(ofile.name),4)=extension Then
  fso.DeleteFile oFile, True
End If
Next

For Each subFolder In oFolder.SubFolders
DeleteFiles subFolder.Path, cutoffdate, extension
If (SubFolder.Files.Count = 0) and (SubFolder.SubFolders.Count=0) And (SubFolder.DateCreated < cutoffdate) Then
msgbox "deleting " & subfolder.name & " created on " & subfolder.DateCreated
call SubFolder.Delete()
End If
Next

End Function

Open in new window

DanNetwork Engineer

Author

Commented:
same thing, but I just couldn't get it to work.
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
@afacts

==> same thing, but I just couldn't get it to work.\

Did you have a problem with my BAT file, or did you drop that and are only interested in a VBS solution now?

~bp
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Did you take a look at the DELAGE32 utility, it can handle everything you specified.

http://home.mnet-online.de/horst.muc/win/delage.htm
http://www.horstmuc.de/wbat32.htm

~bp
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
"just couldnt get it to work"

what does it do.  does it not do what you want? Does it give an error when run?

Commented:
Steve: Do you want 10 newest files.... or files from last 10 days.
afacts: same thing...


@afacts:
Both statments are not the same thing, and the scripts required are different.

What if you have a 100 new files yesterday?
What if your newest files are last month?
DanNetwork Engineer

Author

Commented:
billprew, I did look at that utility, but I'm trying to make things as simple as possible, the reason why I want just a batch file is beause I can use the windows schedular to run when I want.

Steve, I want the 10 newest files, not the last 10 days because if there's any issues with the backups and they don't run for a few days or longer, then using the last 10 days will delete everyhing.  Can you make it just to keep the 10 newest files, and delete everything else.  I can change the paramter from 10 to something else if I want.
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
Isn't that what the batch script in the previous Q did for you?

The script as it stands does 10 days because you asked for "to be able to specify how many days I want to keep files in the directory (newest files of course by modify date)".

So just to confirm you want to be able to have a script which checks one dir and all subdirs and keeps newest 10 (or other fixed no. for all dirs) in each dir?

Steve

Commented:
This will creat 40 test files, then delete all but the last 10 created, excluding the batch file.

@ECHO OFF

REM CREATING TEST FILES
   FOR /L %%A IN (10,1,50) DO (
      PING 127.0.0.1 -n 1 >NUL
      ECHO CREATING %%A.TXT
      ECHO.>%%A.TXT
   )

REM DELETING ALL BUT NOT THE 10 FILES
   FOR /F "skip=10 delims=" %%A IN ('DIR /b /s /o-d *.* ^| FINDSTR /i /v "%~nx0"') DO (
      ECHO DELETING "%%~fA"
      DEL /f /s "%%~fA" >NUL
   )

PAUSE
EXIT

Open in new window

Commented:
After reviewing my script with the following, I found that it can not be applied with sub-folders:
 
@ECHO OFF

REM CREATING TEST FILES
   FOR /L %%A IN (10,1,50) DO (
      PING 127.0.0.1 -n 1 >NUL
      ECHO CREATING %%A.TXT
		IF %%A == 20 (
			ECHO.>.\TEST\%%A.TXT
			) ELSE (
				IF %%A == 45 (
					ECHO.>.\TEST\%%A.TXT
				) ELSE (
					ECHO.>%%A.TXT
				)
			)
		)		
   )

PAUSE

REM DELETING ALL BUT NOT THE 10 FILES
   FOR /F "skip=10 delims=" %%A IN ('DIR /a-d /b /s /o-d *.* ^| FINDSTR /i /v "%~nx0"') DO (
      ECHO DELETING "%%~fA"
      DEL /f /s "%%~fA" >NUL
   )

PAUSE
EXIT

Open in new window


So if you need to apply this to sub-directory, an other approach will be required.

If not, just remote the /s in : 'DIR /b /s /o-d *.*
 
@ECHO OFF

REM CREATING TEST FILES
   FOR /L %%A IN (10,1,50) DO (
      PING 127.0.0.1 -n 1 >NUL
      ECHO CREATING %%A.TXT
      ECHO.>%%A.TXT
   )

REM DELETING ALL BUT NOT THE 10 FILES
   FOR /F "skip=10 delims=" %%A IN ('DIR /b /o-d *.* ^| FINDSTR /i /v "%~nx0"') DO (
      ECHO DELETING "%%~fA"
      DEL /f /s "%%~fA" >NUL
   )

PAUSE
EXIT

Open in new window

DanNetwork Engineer

Author

Commented:
Hi Steve, yes, that's what your other script I thought did, but it just didn't work.  I'll try it again, as i have to many things going on.
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
know the feeling.... Will adjust one to do 10 files in each subdir...
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
Ok.  looking back at the previous Q it seems you selected the one answer and we never got to the bottom of why you had issues with the other suggestions.  99% of it I would suggest is that you chose a folder with a space in it but did not put " " around it.  Can we try again then please with this batch.

As it stands it should leave the newest 7 files in each dir under the "e:\mailflow backups" folder that are called .bak, anything else stays there the same.

Just running a test over this but posting for now anyway.

Steve

@echo off (need to change the below to the locations needed and file types)

call :delolder 7 "E:\mailflow backups" "bak"
exit /b

:delolder
set type="%~3"
set thedir="%~2"
set keep=%~1
for /f "delims=" %%D in ('dir %thedir% /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% delims=" %%a in ('dir "%%~fD\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%%~D\%%~a"
)
echo Working on root dir %thedir%
for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%thedir%\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"
exit /b

Open in new window

Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
OK used this code to make some test files:
 
@echo off
e:
cd \
md "mailflow backups"
cd "mailflow backups"
for /l %%d in (1,1,10) do (
  md dir%%d
  for /l %%n in (1,1,5) do echo. > dir%%d\file%%n.txt
  for /l %%n in (1,1,30) do echo. > dir%%d\backup%%n.bak
)

Open in new window


and then the code here to clean it up:
 
 
@echo off (need to change the below to the locations needed and file types)

call :delolder 7 "E:\mailflow backups" "bak"
exit /b

:delolder
set type="%~3"
set thedir="%~2"
set keep=%~1
for /f "delims=" %%D in ('dir %thedir% /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% delims=" %%a in ('dir "%%~fD\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%%~D\%%~a"
)
echo Working on root dir %thedir%
for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%thedir%\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"
exit /b

Open in new window


which left these files in the structure... i.e. only bak files affected.  Latest 7 files remaining.
 
Volume in drive E is ReadyBoost
 Volume Serial Number is D89A-2A75

 Directory of E:\mailflow backups

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:31                 0 1.txt
03/11/2011  00:31    <DIR>          dir1
03/11/2011  00:31    <DIR>          dir10
03/11/2011  00:31    <DIR>          dir2
03/11/2011  00:31    <DIR>          dir3
03/11/2011  00:31    <DIR>          dir4
03/11/2011  00:31    <DIR>          dir5
03/11/2011  00:31    <DIR>          dir6
03/11/2011  00:31    <DIR>          dir7
03/11/2011  00:31    <DIR>          dir8
03/11/2011  00:31    <DIR>          dir9
               1 File(s)              0 bytes

 Directory of E:\mailflow backups\dir1

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir10

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir2

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir3

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir4

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir5

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir6

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir7

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir8

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

 Directory of E:\mailflow backups\dir9

03/11/2011  00:31    <DIR>          .
03/11/2011  00:31    <DIR>          ..
03/11/2011  00:30                 3 backup24.bak
03/11/2011  00:30                 3 backup25.bak
03/11/2011  00:30                 3 backup26.bak
03/11/2011  00:30                 3 backup27.bak
03/11/2011  00:30                 3 backup28.bak
03/11/2011  00:30                 3 backup29.bak
03/11/2011  00:30                 3 backup30.bak
03/11/2011  00:30                 3 file1.txt
03/11/2011  00:30                 3 file2.txt
03/11/2011  00:30                 3 file3.txt
03/11/2011  00:30                 3 file4.txt
03/11/2011  00:30                 3 file5.txt
              12 File(s)             36 bytes

     Total Files Listed:
             121 File(s)            360 bytes
              32 Dir(s)       5,332,992 bytes free

Open in new window


Steve

Commented:
@afacts:

I just spent some of my time scripting something to help you.

Would you mind giving me some feedback?

Cheers,
Rene
DanNetwork Engineer

Author

Commented:
ReneGe,
I was a little lost with your script, as I don't need the script to create files.
DanNetwork Engineer

Author

Commented:
Steve, the script below worked, it deleted all hte .bak files in that directory and everyother.
Thanks.  I'm assuming if I want to delete every file in the directory, I can just remove hte "bak", and then it does everything in that location, right?

@echo off (need to change the below to the locations needed and file types)

call :delolder 7 "E:\mailflow backups" "bak"
exit /b

:delolder
set type="%~3"
set thedir="%~2"
set keep=%~1
for /f "delims=" %%D in ('dir %thedir% /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% delims=" %%a in ('dir "%%~fD\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%%~D\%%~a"
)
echo Working on root dir %thedir%
for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%thedir%\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"
exit /b

Commented:
It creats file to test the script. Therefore, you need to test a script before running it in real life.
Here would be the script for production.
As you can see, I just removed the file creation portion.

@ECHO OFF

REM DELETING ALL BUT NOT THE 10 FILES
   FOR /F "skip=10 delims=" %%A IN ('DIR /b /o-d *.* ^| FINDSTR /i /v "%~nx0"') DO (
      ECHO DELETING "%%~fA"
      DEL /f /s "%%~fA" >NUL
   )

PAUSE
EXIT

Open in new window

Commented:
After reviewing Steve's script, (if i'm not mistaking) is doing exactly the same thing as my script. However, it is much more sophisticated. And I am impressed, one again, about his abilities.

Inspired by his script, I would add the SET of the extension in a variable.

Cheers,
Rene
@ECHO OFF
SET Type=bak
REM DELETING ALL BUT NOT THE 10 FILES
   FOR /F "skip=10 delims=" %%A IN ('DIR /b /o-d *.%Type% ^| FINDSTR /i /v "%~nx0"') DO (
      ECHO DELETING "%%~fA"
      DEL /f /s "%%~fA" >NUL
   )

PAUSE
EXIT

Open in new window

DanNetwork Engineer

Author

Commented:
Thanks ReneGe,  I'll test it on Monday, as I have to go for the day,a nd I'm taking tomorrow off.
I'll reply on Monday.

Commented:
Enjoy your weekend long!
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
@ReneGe

I'm curious about your approach.  I thought the requirements were to process subfolders as well as the base folder, although it has been a little confusing for me following this one.  If that's true, I only see you going after the files on the base folder?

Also, what's up with the /S on the DEL, that would delete the same named file from any subfolders, but having trouble linking that to a requirement?

~bp
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
"I'm assuming if I want to delete every file in the directory, I can just remove hte "bak", and then it does everything in that location, right?"

If you use "*" for the extension if you want all files. "" would look for *. , i.e. files with no extension.

Effectively it is doing a dir of *. + whatever you enter in this variable in each subdir.

Steve

Commented:
@Bill
-If you look further, I removed it as it was a mistake on my part.
-I may have skipped it, but I did not find deleting files in subfolders
-Yes, I'm only going after the files in the base folder
-"/S on the DEL". You are right, I wanted the switch for silent mode, which is not /S but /Q for quite. Thanks for pointing it out.

Thanks for your feedbacks. :)

Commented:
@Bill:
About my answer:
-If you look further, I removed it as it was a mistake on my part.

You ment about the DEL not the DIR.

I guess I should stop talking and go to bed.

Cheers
Test your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016
Commented:
Okay, I was trying not to post on this one, but I can't help myself.  Here's how I would go about it.

Just adjust the 3 SET statements at the top as you desire.  It deletes files from the specified folder, and all subfolders under it.

Place the BAT file in a different folder than the BaseDir (or any of it's children) so it doesn't get deleted.

@echo off
set BaseDir=C:\Temp
set FilesToKeep=7
set FileFiler=*.*
for /R "%BaseDir%" %%D in (.) do (
  echo Processing directory "%%~fD"
  for /F "skip=%FilesToKeep% tokens=*" %%F in ('dir /A-D /O-D /B "%%~fD\%FileFilter%" 2^>NUL') do (
    del "%%~fD\%%~F"
  )
)

Open in new window

~bp

Commented:
@Bill
I am puzzled about "2^>NUL" in regards to how would you add "^| FINDSTR /i /v "%~nx0"" in the line 7, to skip the batch file name?

Cheers
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
The 2^NUL just chucks any errors into the bit bucket.

I did not try to exclude the BAT folder, better to place it in a separate folder in my opinion.  Or use a filter of something that doesn't include *.BAT files will work as well.

~bp

Commented:
@Bill
My idea was to excluse the BAT file, not the folder. Maybe I did it wrong. Ok I'm done for today. Going to bed now.

Commented:
@afacts:
Just before slipping into the Wonderfull World Of Disney, I'd like to understand something.

-Do you need to keep the 10 newest files in each sub-folders and delete the rest?
For example, if you have 10 subfolder containing 20 files each, only the newest 100 files would not be deleted

-Do you need to include sub-folders anyhow?
For example: If not, only the files in the main folder would be deleted, exept the 10 newest ones

-Do you need to delete all the files, in all subfolders, excluding the 10 newest ones?
For example, if you have 100 subfolder containing 200 files each, only 10 files in total would not be deleted

Of coarse, all options excludes deleting the batch file all by it self!!

Cheers
Steve KnightIT Consultancy
CERTIFIED EXPERT
Commented:
Glad it worked for you before, if you really want to exclude the batch file from being deleted I have added an "if exist" in the base dir cleanup bit.

Steve
@echo off (need to change the below to the locations needed and file types)

call :delolder 7 "E:\mailflow backups" "*"
exit /b

:delolder
set type="%~3"
set thedir="%~2"
set keep=%~1
for /f "delims=" %%D in ('dir %thedir% /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% delims=" %%a in ('dir "%%~fD\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%%~D\%%~a"
)
echo Working on root dir %thedir%
for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%thedir%\*.%type%" /a-d /o-d /b 2^>NUL') do if "%%~nxa" NEQ "%~nx0" DEL "%thedir%\%%~a"
exit /b

Open in new window

DanNetwork Engineer

Author

Commented:
Sorry for the late response, I've  been swamped.  I tried the last bat file code, the one above, but it didn't do anything, it didn't work, I copied the results in the attached cmd screen.

cmd output
DanNetwork Engineer

Author

Commented:
Bills worked fine, so I'm just going to use that one.

Thanks everyone for your help, I really appreciate it!!!
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
I noticed a couple of bugs in Steve's code (the kids may have been helping him again :-> ), give this changed version a try.

@echo off 
REM need to change the below to the locations needed and file types

call :delolder 7 "E:\mailflow backups" "*"
exit /b

:delolder
set type=%~3
set thedir=%~2
set keep=%~1
for /f "delims=" %%D in ('dir "%thedir%" /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% delims=" %%a in ('dir "%%~fD\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%%~D\%%~a"
)
echo Working on root dir %thedir%
for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%thedir%\*.%type%" /a-d /o-d /b 2^>NUL') do if "%%~nxa" NEQ "%~nx0" DEL "%thedir%\%%~a"
exit /b

Open in new window

~bp
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Sorry, posted in between your posts.  Glad mine worked out, I resisted the urge to just say "use mine" and decided to try and adjust Steve's/.  So hopefully you have at least 2 viable options.

Thanks for the feedback.

~bp
DanNetwork Engineer

Author

Commented:
Thanks bill, the last post you did worked as well.

Thanks everyone again, much appreciated, you guys are great!!!!!!!!!!!!!!
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
OK, firstly the first line should just be

@echo off

i.e. the comment was for removing!

and somehow we've ended up adding double quotes all over the place, my bad!

Try this. Don't have time to run test tonight as it's 1am but will look back tomorrow if needed.

Steve


@echo off (need to change the below to the locations needed and file types)

call :delolder 7 "E:\mailflow backups" "*"
exit /b

:delolder
set type=%~3
set thedir=%~2
set keep=%~1
for /f "delims=" %%D in ('dir "%thedir%" /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% delims=" %%a in ('dir "%%~fD\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%%~D\%%~a"
)
echo Working on root dir %thedir%
for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%thedir%\*.%type%" /a-d /o-d /b 2^>NUL') do if "%%~nxa" NEQ "%~nx0" DEL "%thedir%\%%~a"
exit /b

Open in new window

Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
Looks like I was a bit slow there!

Steve
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Wasn't sure if you were off for the night or not Steve...

~bp

Commented:
Guy's (Bill & Steve), I'm currently having fun!!  ;)
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
+1

~bp
DanNetwork Engineer

Author

Commented:
thanks Steve, your last post worked.

You guys are awesome, thank you for your help, now I have 3 different versions that all work. :)

Commented:
@afacts:

Don't be shy posting your questions. We'll be glad to help!!

Lot of cheers,
Rene

Commented:
Let's play.. Who's the the quickest shooter!

Commented:
Meaning "Bill or Steve"...  ;)
@afacts: (inside thang!!)

Commented:
Ready...? Go!!
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Let's be fair, Steve's under the covers resting by now...

~bp

Commented:
It's just a game Bill !!
I'm curious... What means "under the covers resting by now"???
Lots of cool cheers!!
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
Where Steve lives, it's bed time now.

~bp

Commented:
lol. Oh, seems you'r in da lucky pit!
Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
At the moment, but Steve shoots ahead in the "morning" when he is online hours ahead of me...

~bp

Commented:
Ok then, I'll keep some statistical bullets for tomorrow AM. :)
Steve KnightIT Consultancy
CERTIFIED EXPERT

Commented:
haha, well a few hours worth anyway if I'm lucky.
'bang"
:-)

Still 18k or so to go to the 1m mark here :-(

At least theree are a few hours before you all get up again but I've got BillDL and PaulTomasi in GMT (aka the 'proper' one....) time zone amongst others... Though not necessarily earth based all the time ;)