batch file to delete all files older then x days (modify date)

I am running windows server 2008 R2 and I have some folders that I have backup files that I need a script to run to delete any file lets say older then 10 days or what ever.  I found a few scripts online, but none are simple and robust.  Any suggestions of a simple batch script that will delete any file in the root folder and any other folder older then x days (modified date)?
DanNetwork EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bill PrewCommented:
How about using a small and simple utility like DELAGE32?

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

~bp
0
Bill PrewCommented:
And if you really want a pure BAT approach here's one from a prior solution I provided.  Adjust the SET's near the top for your folder and age needs.

NOTE: This won't delete anything yet, but will just display the list of files that would be deleted on the screen.  This is for testing.  If it looks right, then remove the REM in front of the DEL line.

@echo off
setlocal EnableDelayedExpansion

REM Define base for folders, and days to keep old folders
Set BaseDir=c:\temp
set DaysToKeep=10

REM Get todays date (MM/DD/YYYY), convert to julian for age checks
call :jDate jToday %DATE:~-10%

REM Process all Files in the directory, delete if old
for /F "tokens=*" %%A in ('dir /s /b /a-d "%BaseDir%\*.*"') do (
  call :jDate jFile %%~tA
  set /A FileAge = !jToday! - !jFile!
  if !FileAge! GTR %DaysToKeep% (
    ECHO File:[%%A] is [!FileAge!] days old and would be deleted
    REM del "%%~A"
  )
)

REM Done
exit /b

REM Subroutine to calculate julian date
:jDate return-variable date-string(MM/DD/YYYY) 
  set DateStr=%~2
  set yy=%DateStr:~6,4%
  set /A mm=1%DateStr:~0,2%-100
  set /A dd=1%DateStr:~3,2%-100
  set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
  set /a %~1=dd-32075+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3*((yy+4900+(mm-14)/12)/100)/4
  exit /b

Open in new window

~bp
0
Steve KnightIT ConsultancyCommented:
Delage32 is good and batch file clever but for another angle using the built-in date handling ability of VBScript rather than some clever code that you might not understand in years to come I have this script of mine here:

http://scripts.dragon-it.co.uk/links/batch-delete-files-older-than

Download delolder.vbs, amend the path and age parameters and run it.... can soon run from explorer or from a batch file with:

cscript //nologo delolder.vbs

The line here which takes all files over 1 month old

 DeleteFiles  "c:\temp",DateAdd("m", -1, Date)

Can be for instance

 DeleteFiles  "c:\temp",DateAdd("d", -10, Date)

to remove anything over 10 days old from c:\temp or subdirs.

Another option is to keep the last 10 files by date in a dir etc. which is simple in batch file:

http://scripts.dragon-it.co.uk/links/batch-versioning-backup

Steve
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

DanNetwork EngineerAuthor Commented:
The reason I wanted a .bat file is because I don't need to download any special software or remember anything months or years from now.  I can just open the batch file and figure out what is doing.

I'm guessing there's no simpler way to modify the batch file to be any simpler?  I guess the one you provided is simple enough, does it also perform the same funtion in all subdirectories as well, so I don't have to have manually enter the path of each location?
0
Steve KnightIT ConsultancyCommented:
The VBS btw is just a case of:
 
' 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:\temp",DateAdd("m", -1, Date)

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

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

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

For Each oFile in oFolder.Files
If ofile.DateCreated < cutoffDate Then
fso.DeleteFile oFile, True
End If
Next

For Each subFolder In oFolder.SubFolders
DeleteFiles subFolder.Path, cutoffdate
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


and run with  cscript.exe //nologo delolder.vbs  from a batch file.

Or the possible way of just keeping the last 10 files say, if easier, could be done in one or two lines of batch but I made it a bit clearer in my script above, i.e. the part of the script I linked to that does it is:

 
' 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:\temp",DateAdd("m", -1, Date)

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

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

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

For Each oFile in oFolder.Files
If ofile.DateCreated < cutoffDate Then
fso.DeleteFile oFile, True
End If
Next

For Each subFolder In oFolder.SubFolders
DeleteFiles subFolder.Path, cutoffdate
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


Steve
@echo off
setlocal enabledelayedexpansion

REM Keep only newest files in the "old" directory:
set thedir="D:\backups"
set keep=5
set count=1

for /F "tokens=* delims=" %%a in ('dir %thedir% /a-d /o-d /b') do (
 if !count! GTR %keep% echo DEL %%a
 set /A count=count+1
)

echo All Done.
pause

Open in new window

0
Steve KnightIT ConsultancyCommented:
Hm, clearly the embedded bits went a bit haywire there.  The second please ignore, 3rd is what should be there.

Steve
0
DanNetwork EngineerAuthor Commented:
so are you saying I can the following and slap it into a .bat file and I'm good to go?

@echo off
setlocal enabledelayedexpansion

REM Keep only newest files in the "old" directory:
set thedir="D:\backups"
set keep=5
set count=1

for /F "tokens=* delims=" %%a in ('dir %thedir% /a-d /o-d /b') do (
 if !count! GTR %keep% echo DEL %%a
 set /A count=count+1
)

echo All Done.
pause
0
Steve KnightIT ConsultancyCommented:
Yes as it stands that will delete anything other than the 5 newest files in a directory d:\backups.  That may give you what you want, or not depends on what the files are.

Effectively it takes a dir listing of all files (not dirs) in a directory in bare format in reverse date order
It skips the first no. from the keep line and then deletes the rest one by one.

It can actually be simplified futher as below. You need to remove the word "echo" before the del command once you are happy with which files it deletes - echo will make it show the command rather than to run it..

Steve

@echo off
REM Keep only newest files in the "old" directory:
set thedir="D:\backups"
set keep=5

for /F "skip=%keep% tokens=* delims=" %%a in ('dir %thedir% /a-d /o-d /b') do echo DEL "%%~a"

echo All Done.
pause

Steve
0
DanNetwork EngineerAuthor Commented:
ok, the last one you gave me is good, let's say I only want to delete .tib files, and nothing else in a directory, how would I do that?  Let's say I only need to delete a certain type of file?
0
Steve KnightIT ConsultancyCommented:
Sure, it is just a dir command it reads so anything you can do to a dir command.

In that case change the set line to:

set thedir="D:\backups\*.tib"

You can test what it is working on with:

dir "d:\backups\*.tib" /a-d /o-d /b

The first "n" lines of this are skipped and then everything else is deleted.

Steve
0
Bill PrewCommented:
==> I'm guessing there's no simpler way to modify the batch file to be any simpler?  
==> I guess the one you provided is simple enough, does it also perform the same funtion in all
==> subdirectories as well, so I don't have to have manually enter the path of each location?

Yes, the BAT solution I provided drills into all subdirectories.

There isn't a much simpler way to do this with native BAT capabilities.

~bp
0
DanNetwork EngineerAuthor Commented:
bp, so to have your script only delete .tib or what ever extension files, what do I have to modify for that?
Is it just here:  BaseDir%\*.*" change that to BaseDir%\*.tib"
0
Bill PrewCommented:
Change this line:

for /F "tokens=*" %%A in ('dir /s /b /a-d "%BaseDir%\*.*"') do (

to:

for /F "tokens=*" %%A in ('dir /s /b /a-d "%BaseDir%\*.tib"') do (

If you will be changing that often then we could adjust it to be easier at the top of the script.

~bp
0
DanNetwork EngineerAuthor Commented:
I tried both scripts, and it's not deleting any files?
0
Bill PrewCommented:
From earlier post:

NOTE: This won't delete anything yet, but will just display the list of files that would be deleted on the screen.  This is for testing.  If it looks right, then remove the REM in front of the DEL line.

~bp
0
DanNetwork EngineerAuthor Commented:
so everywhere where it says del I have to remove? Or is it only in front of the "process"
How about here, REM del "%%~A
Anywhere else?
0
DanNetwork EngineerAuthor Commented:
I tried that, I removed the REM but still doesn't delete.
0
Bill PrewCommented:
Okay, let's check something.  If you open a DOS command prompt window, and type

ECHO %DATE%

exactly what is displayed?

~bp
0
DanNetwork EngineerAuthor Commented:
wed 10/26/2011
0
DanNetwork EngineerAuthor Commented:
I got Steve's script to work, so maybe I'll just use his.

Steve, does it also delete every other file that matches the criteria in all subdirectories?
0
DanNetwork EngineerAuthor Commented:
I tested it and it didn't.
0
Bill PrewCommented:
Date format looks fine.

I just tested it here and it worked fine.

You changed these two lines at the top, right?

Set BaseDir=c:\temp
set DaysToKeep=10

Did you change anything else?

~bp
0
DanNetwork EngineerAuthor Commented:
yes, I changed those two lines and then removed the REM before Process and before del "%%~A"
0
DanNetwork EngineerAuthor Commented:
I'm leaving for the day, so I'll respond tomorrow. Thanks.
0
Bill PrewCommented:
The REM before process should not have been removed, only the following one:

    REM del "%%~A"

~bp
0
Steve KnightIT ConsultancyCommented:
sorry i thought from your last comment it was only needed to be files in the dir though in your original q it did say subdirs too.

My vbs will work as posted.  the batch will need just the word echo removing in front of the del command as stated above, i.e. Run it first, make sure it SHOWS youthe right files then removing the echo makes it work.

To do subdirs it just need a /s adding to the dir command.  will post amendment in full when i can copy/paste on pc in bit.

steve
0
DanNetwork EngineerAuthor Commented:
bp,
Here's how I have the script, but it's still not working:

@echo off
setlocal EnableDelayedExpansion

REM Define base for folders, and days to keep old folders
Set BaseDir=C:\test
set DaysToKeep=4

Get todays date (MM/DD/YYYY), convert to julian for age checks
call :jDate jToday %DATE:~-3%

REM Process all Files in the directory, delete if old
for /F "tokens=*" %%A in ('dir /s /b /a-d "%BaseDir%\*.*"') do (
  call :jDate jFile %%~tA
  set /A FileAge = !jToday! - !jFile!
  if !FileAge! GTR %DaysToKeep% (
    ECHO File:[%%A] is [!FileAge!] days old and would be deleted
    del "%%~A"
  )
)

REM Done
exit /b

REM Subroutine to calculate julian date
:jDate return-variable date-string(MM/DD/YYYY)
  set DateStr=%~2
  set yy=%DateStr:~6,4%
  set /A mm=1%DateStr:~0,2%-100
  set /A dd=1%DateStr:~3,2%-100
  set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
  set /a %~1=dd-32075+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3*((yy+4900+(mm-14)/12)/100)/4
  exit /b
0
DanNetwork EngineerAuthor Commented:
steve, is this what you were referring to, to do subdirectories as well?

@echo off (need to remove the echo before the DEL below)
REM Keep only newest files in the "old" directory:
set thedir=C:\test /s
set keep=4

for /F "skip=%keep% tokens=* delims=" %%a in ('dir %thedir% /a-d /o-d /b') do DEL "%%~a"

All Done.
0
DanNetwork EngineerAuthor Commented:
Steve,

That worked, the only problem is that it deleted everything in the subdirectory, it didn't leave the 4 newest files there. I'll just have to have this script in every directory I need cleaned up I guess.
0
Bill PrewCommented:
==> Here's how I have the script, but it's still not working:

Silly question, but are there files in "C:\TEST" that were not modified in the last 4 days?

Can you do a DIR C:\TEST and post the result here.

~p
0
DanNetwork EngineerAuthor Commented:
Yes, there's files in that directory, here you go.

C:\test>dir
 Volume in drive C has no label.
 Volume Serial Number is F689-3EBC

 Directory of C:\test

10/27/2011  08:43 AM    <DIR>          .
10/27/2011  08:43 AM    <DIR>          ..
08/30/2011  09:30 AM            37,034 ASSET Transfer Form.pdf
10/27/2011  08:36 AM               974 delete.bat
10/27/2011  08:42 AM               252 deleteFiles.bat
05/10/2011  01:17 PM             3,244 Loud.tsk.xml
08/30/2011  05:41 PM           342,512 NetAdmin-Master Spreadsheet.xlsx
10/27/2011  08:44 AM               971 newdel.bat
05/10/2011  01:17 PM             3,249 Normal.tsk.xml
09/20/2011  05:13 PM             3,251 One_Ring.tsk.xml
09/22/2011  06:41 PM               696 One_Ring_Monitor.prf.xml
05/10/2011  01:17 PM             3,222 On_Call.tsk.xml
08/15/2011  02:23 PM           111,838 PTO.pdf
09/29/2011  04:39 PM            21,976 PurchaseRequisition.docx
05/10/2011  01:17 PM             3,199 Sleep.tsk.xml
05/10/2011  01:17 PM               368 Sound_Profile.tsk.xml
10/25/2011  06:02 PM           138,048 sqlerror.jpg
10/27/2011  08:42 AM    <DIR>          test2
05/10/2011  01:17 PM             3,266 Vibrate.tsk.xml
05/10/2011  01:17 PM               776 Volume_Buttons.prf.xml
05/10/2011  01:17 PM             3,244 Work.tsk.xml
              18 File(s)        678,120 bytes
               3 Dir(s)  66,325,499,904 bytes free

C:\test>
0
Steve KnightIT ConsultancyCommented:
Sorry yes thinking about it it would keep the newest four files from the top level dir only.... was busy earlier.

Is there only top level extra subdirs, or additonal ones below that?

i.e.

C:\test\dir1
c:\test\dir2
C:\test

or also
c:\test\dir1\dirb

And do you want each dir to keep the four newest files say?

In which case we just need to run the check for each subdir, or multiple subdirs if there are any

Steve
0
Bill PrewCommented:
Okay, reviewing your version of my scriot it looks like you changed this line:

call :jDate jToday %DATE:~-10%

to this:

call :jDate jToday %DATE:~-3%

that will not work, not sure if you did that for a reason or just a typo, but put it back the way I wrote it and try again please.  (it has nothing to do with the days you are trying to keep that is al controlled by the SET at the top)

~bp
0
Steve KnightIT ConsultancyCommented:
Try this in fact:

@echo off

REM Keep only newest files in the "old" directory:


set thedir=C:\test

set keep=2

for /f "delims=" %%D in ('dir %thedir% /ad /b /s') do (

  echo Working on dir %%~fD

  for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%%~fD" /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%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"


echo All Done.

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Steve KnightIT ConsultancyCommented:
That keeps the 2 newest files in the top dir and each sub dir btw.
0
DanNetwork EngineerAuthor Commented:
bp,  got it, I changed it back and it did work. It worked the first time I did it, then after I put back some files for more testing, it's not working anymore,

steve,
here's a file structure for example,
E:\images\judah\daily
E:\images\levi\weekly
E:\images\w1\wednesday
So I'll have the .bat file in the images directory.  I noticied it only keeps the last 5 days, but is there a way to keep the newest 5 copies instead. I was thinking about it and if for some reason, my backup jobs don't run for a few days, or a week, the script will run and delete all my backups, when at least I still want to have the newest 5 or 7 backups, is that possible?
0
Steve KnightIT ConsultancyCommented:
my batch script keeps the newest 5 or whatever nyou set newest files not those 5 days old.

If you want to do all the subdirs but not the images dir itself use my last example bur remove the second for command.

Steve.
0
Bill PrewCommented:
==> bp,  got it, I changed it back and it did work. It worked the first time I did it, then after I put
==> back some files for more testing, it's not working anymore,

Okay, the fact that it worked the first time (and my testing here) indicates the script is working.

Review your test files before running it and make sure there are some that are old enough. Bear in mind that this is checking the "last updated" date of the file, which might have gotten updated depending on how you added more files.

~bp
0
DanNetwork EngineerAuthor Commented:
it doesn't check the modified date?
0
DanNetwork EngineerAuthor Commented:
Thanks guys, thanks so much for your help, we've wasted enough time on this request.  I got Steve's to work, so I'll just use that one. Thanks to both of you, that's why I thought it would be fair to just split the points half/half.

Thanks a million!
0
DanNetwork EngineerAuthor Commented:
Steve, I did forget to ask, is there a way to tell the script that in a different directory, if I want it to keep 3 day in folder A, but I want it to keep files 7 days in folder B, is that possible, or just use your original script for each folder, as in thinking about it, this will not work, as I have folders that I want the files there to retain longer days in certain folder compared to others.
0
DanNetwork EngineerAuthor Commented:
last question, it only deletes files, and not folders, right?
0
Bill PrewCommented:
Yes, modified date is the same as updated date.

~bp
0
Steve KnightIT ConsultancyCommented:
Thanks, as longas you're happy, fine by me...   As to your last comment you could make it into a sub perhaps and then call it for each dir, e.g.

@echo off

call :delolder 5 "c:\test\dir1"
call :delolder 7 "c:\test\dir2"

exit /b

:delolder

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% tokens=* delims=" %%a in ('dir "%%~fD" /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%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"
exit /b
0
Steve KnightIT ConsultancyCommented:
And re: folders.... yes it only does files, never folders.

Steve
0
DanNetwork EngineerAuthor Commented:
sweet, that's easier then having 4 different scripts.  And if I want only .tib's deleted, I just need to do the followig, right:



@echo off

call :delolder 5 "c:\test\dir1\testfolder\*.tib"
call :delolder 7 "c:\test\dir2\daily\*.tib"

exit /b

:delolder

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% tokens=* delims=" %%a in ('dir "%%~fD" /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%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"
exit /b
0
DanNetwork EngineerAuthor Commented:
so if I have 4 locations, is this how the script looks like?  I'm assuming the set thedir="%~4", and not 2, right, I need to change that based on the directories I use.  Do I need to change anything else.
@echo off

call :delolder 8 "C:\test\judah\daily\*.xml"
call :delolder 4 "C:\test\judah\weekly\*.xml"
call :delolder 8 "C:\test\levi\daily\*.xml"
call :delolder 4 "C:\test\levi\weekly\*.xml"

exit /b

:delolder

set thedir="%~4"
set keep=%~1
for /f "delims=" %%D in ('dir %thedir% /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%%~fD" /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%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"
exit /b
0
Steve KnightIT ConsultancyCommented:
No.  set thedir="%~2" says to get the second parameter of the line it is called with.  %~1 is the first parameter.

That will delete all from top level and all subdirs under "C:\test\judah\daily" and keep 8
If you want it to be specific files we are going to need to amend it again I guess.

Do you only want specific directory then, or subdirs too?

Sub dirs

@echo off

call :delolder 8 "C:\test\judah\daily" "*.xml"
call :delolder 4 "C:\test\judah\weekly" "*.xml"
call :delolder 8 "C:\test\levi\daily" "*.xml"
call :delolder 4 "C:\test\levi\weekly" "*.xml"

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

Subdirs too:

@echo off

call :delolder 8 "C:\test\judah\daily" "*.xml"
call :delolder 4 "C:\test\judah\weekly" "*.xml"
call :delolder 8 "C:\test\levi\daily" "*.xml"
call :delolder 4 "C:\test\levi\weekly" "*.xml"

exit /b

:delolder
set type="%~3"
set thedir="%~2"
set keep=%~1

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


Steve
0
Steve KnightIT ConsultancyCommented:
Sorry make that

call :delolder 8 "C:\test\judah\daily" "xml"
call :delolder 4 "C:\test\judah\weekly" "xml"
call :delolder 8 "C:\test\levi\daily" "xml"
call :delolder 4 "C:\test\levi\weekly" "xml"

as it adds the *.
0
DanNetwork EngineerAuthor Commented:
here's the locations I need it to run in, and the files to delete and how long to retain in each directory.

E:\images\judah\daily\*.tib   (keep 10 newest files)
E:\images\judah\weekly\*.tib (keep 6 newest files)
E:\images\levi\daily\*.tib  (keep 10 newest files)
E:\images\levi\weekly\*tib  (keep 6 newest files)

I would like to know how it works, so if I need to may any changes, so I can do that.  Thanks.
0
Steve KnightIT ConsultancyCommented:
kids bath time... Should be self explanatory from previous example for no. Of days, path, file type in eacj call line i think but ask if not.

I think i explained how the script itself worked earlier on.... If not say.

Steve
0
DanNetwork EngineerAuthor Commented:
got it to work, thanks.
0
DanNetwork EngineerAuthor Commented:
actually, I ran the script in production and it deleted my newest files, and kept my oldest ones, that's not good, that's terrible......  So it looks like it keeps the oldest files, not the newest ones.
0
DanNetwork EngineerAuthor Commented:
I noticied with this version of the script, the script also deletes itself, that's not good.
Is there a way to tell the script to not delete itself?

@echo off (need to remove the echo before the DEL below)
REM Keep only newest files in the "old" directory:
set thedir=C:\test
set keep=5

for /F "skip=%keep% tokens=* delims=" %%a in ('dir %thedir% /a-d /o-d /b') do DEL "%%~a"

All Done.
0
Steve KnightIT ConsultancyCommented:
well it does if you store it in c:\test

not quite sure where we go now.  question is marked answered, weve gone off at a few tangents with different scripts.

Hmm, did suggest testing before live... But a dir with /o-d should show the newest files first then oldest so leaving the newest ones skipped and deleting the older ones.

Can you post the script that did this?

Please advise

Steve
0
DanNetwork EngineerAuthor Commented:
here's the script:


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

call :delolder 10 "E:\images\judah\daily" "tib"
call :delolder 6 "E:\images\judah\weekly" "tib"
call :delolder 10 "E:\images\levi\daily" "tib"
call :delolder 6 "E:\images\levi\weekly" "tib"

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

Subdirs too:

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

call :delolder 10 "E:\images\judah\daily" "tib""
call :delolder 6 "E:\images\judah\weekly" "tib"
call :delolder 10 "E:\images\levi\daily" "tib"
call :delolder 6 "E:\images\levi\weekly" "tib"

exit /b

:delolder
set type="%~3"
set thedir="%~2"
set keep=%~1

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
0
DanNetwork EngineerAuthor Commented:
then when I try to run one of your previous scripts, this one, it does nothing.  I want it to only delete .bak files, so it doesn't delete itself, as during testing, I had one your scripts delete itself.

@echo off (need to remove the echo before the DEL below)
REM Keep only newest files in the "old" directory:
set thedir=E:\mailflow backups\*.bak
set keep=7

for /F "skip=%keep% tokens=* delims=" %%a in ('dir %thedir% /a-d /o-d /b') do DEL "%%~a"

All Done.

0
DanNetwork EngineerAuthor Commented:
Hi Steve,

When running one of your scripts, it doesn't do anything, and it gives me this error message.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
E:\mailflow backups>deletefilesincurrentdironly.bat
off (need to remove the echo before the DEL below)

E:\mailflow backups>REM Keep only newest files in the "old" directory:

E:\mailflow backups>set thedir=E:\mailflow backups\

E:\mailflow backups>set keep=10

E:\mailflow backups>for /F "skip=10 tokens=* delims=" %a in ('dir E:\mailflow ba
ckups\ /a-d /o-d /b') do DEL "%~a"
The system cannot find the file specified.

E:\mailflow backups>All Done.
'All' is not recognized as an internal or external command,
operable program or batch file.
E:\mailflow backups>



Here's your script that I'm using:
@echo off (need to remove the echo before the DEL below)
REM Keep only newest files in the "old" directory:
set thedir=E:\mailflow backups\
set keep=10

for /F "skip=%keep% tokens=* delims=" %%a in ('dir %thedir% /a-d /o-d /b') do DEL "%%~a"

All Done.
0
DanNetwork EngineerAuthor Commented:
Hi Steve,

This is the only script that actually works, the only thing is, that after the x days I set, if it doesn't get modified, the script will delete itself, as it will be older then let's say 10 days.
How do I fix that?


@echo off

REM Keep only newest files in the "old" directory:


set thedir=C:\test

set keep=4

for /f "delims=" %%D in ('dir %thedir% /ad /b /s') do (

  echo Working on dir %%~fD

  for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%%~fD" /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%" /a-d /o-d /b 2^>NUL') do DEL "%thedir%\%%~a"


echo All Done.
0
Steve KnightIT ConsultancyCommented:
Just put the batch file outside of the directory being deleted...

Steve
0
DanNetwork EngineerAuthor Commented:
So the file needs to be outside of the directory where the files that I want deleted, right?
0
DanNetwork EngineerAuthor Commented:
same thing, but I just couldn't get it to work.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft DOS

From novice to tech pro — start learning today.