Solved

Batch file: delete the oldest files more than 1 week

Posted on 2011-09-20
14
388 Views
Last Modified: 2012-05-12
I need help to write a batch file to delete oldest file more than 1 week or I can determine the period
0
Comment
Question by:egovernment
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
  • 3
  • +1
14 Comments
 
LVL 55

Accepted Solution

by:
Bill Prew earned 500 total points
ID: 36569101
Here's a script I did that is base BAT and does the job, just edit the SETs near the top as needed.  It assumes your date format is MM/DD/YYYY.

@echo off
setlocal EnableDelayedExpansion

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

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 %%A in ("%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
 
LVL 55

Expert Comment

by:Bill Prew
ID: 36569113
Just to clarify, that script will delete ALL files older than the specified number of days.  As I read your question a few more times I'm not clear if that's what you wanted, or if you just want to delete the one oldest file that is more than a specified number of days old?

~bp
0
 
LVL 3

Expert Comment

by:pnorms
ID: 36569117
Are you deleting from a single folder or a tree?
0
Increase Agility with Enabled Toolchains

Connect your existing build, deployment, management, monitoring, and collaboration platforms. From Puppet to Chef, HipChat to Slack, ServiceNow to JIRA, Splunk to New Relic and beyond, hand off data between systems to engage the right people.

Connect with xMatters.

 
LVL 55

Expert Comment

by:Bill Prew
ID: 36569127
Also notice that the actual delete line:

    REM del "%%~A"

has a REM (remark) command on it.  As the script stands it won't delete any files, just ECHO out the info on files that would be deleted, so you can test without losing data.  Once it looks good remove the REM from that line to actually delete the files.

~bp
0
 

Author Comment

by:egovernment
ID: 36572374
Hi billprew

How I make the script delete current folder files
0
 
LVL 55

Expert Comment

by:Bill Prew
ID: 36573428
The script deletes files from

Set BaseDir=c:\temp

did you set that to the folder you want to remove files from?  Or are you saying there is more than one folder involved?

Did you remove the REM from the DEL as mentioned?

~bp
0
 
LVL 3

Expert Comment

by:pnorms
ID: 36574414
This may be a little more what your are looking for and easier to understand:
Just edit lines 6 and 7 to the days you would like to be removed and the file path:
EI:
set days=5
set filepath=C:\windows\logfiles
@echo off
color 47
REM This Script Is Used To Get Rid Of Log Files Older Than 7 Days
:setvars
:: **********  EDIT THESE VARS *************
set days=7
set filepath="C:\test"
:: ********** STOP EDITING *************
echo Press any key to delete the following
echo files from %filepath%
echo -----------------------
forfiles /P %filepath% /S /D -%days% /C "cmd /c dir /B"
echo -----------------------
pause
cls
forfiles /P %filepath% /S /D -%days% /C "cmd /c del /Q @path"
echo Done!
pause
exit
::pn

Open in new window

0
 

Author Comment

by:egovernment
ID: 36934869
Hi pnorms

I need automatically the script identify the current path when I copy the script there
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 36936274
forfiles is part of the Windows RSK, and needs to be downloaded separately, if pnorms suggestion should been used.

You want to always delete the files from the folder the batch file is in? That is (usually) unwise, since you then need to make sure the batch will not delete itself, and further you need to copy the script to each folder you want it have applied to - and then call it from each of those folders. Whatsoever, you would do that by using
   set filepath=%~dp0
resp.
   Set BaseDir=%~dp0
. %0 is the batch file name, %~dp0 is drive and path of the batch file.
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 36936326
Re: http:#a36569101
The necessary change to make sure the batch is not deleted with Bill's code is (only line 15 shown):
  if !FileAge! GTR %DaysToKeep% if not "%~f0" == "%%~fA" (

Open in new window

Re: http:#a36574414
With ForFiles it is more difficult, because we need to use a trick for being able to include double quotes into the command - we are required to provide 0x22 instead of " (replaces line 16 above):
forfiles /P %filepath% /S /D -%days% /C "cmd /c if not 0x22%~f00x22 == @path del @path"

Open in new window

Line 12 is useless that way (if not to say totally wrong). It will list the contents of any folder having files older than x days, which is not as intended. Just omit the command part:
forfiles /P %filepath% /S /D -%days%

Open in new window

(which might also display the batch file itself), or
forfiles /P %filepath% /S /D -%days% /C "cmd /c if not 0x22%~f00x22 == @path echo @path"

Open in new window

0
 
LVL 55

Assisted Solution

by:Bill Prew
Bill Prew earned 500 total points
ID: 36937403
Here's an updated version of my script that will delete files from the folder where the BAT file exists.

@echo off
setlocal EnableDelayedExpansion

REM Define days to keep old files
set DaysToKeep=30

REM Switch to folder where BAT file resides
pushd "%~dp0"

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 %%A in ("*.*") do (
  if "%~nx0" NEQ "%%~nxA" (
    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

Open in new window

~bp
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 36938394
Please be aware the batch files differ in that Bill's solution only applies to the single folder, while the forfiles approach as shown is recursive, so will delete files in subfolders, too. Both can be modified either way.
0
 

Author Comment

by:egovernment
ID: 37020568
I will check all answers
0
 
LVL 55

Expert Comment

by:Bill Prew
ID: 37180624
Any progress?

~bp
0

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Background Information Recently I have fixed file server permission issues for one of my client. The client has 1800 users and one Windows Server 2008 R2 domain joined file server with 12 TB of data, 250+ shared folders and the folder structure i…
While rebooting windows server 2003 server , it's showing "active directory rebuilding indices please wait" at startup. It took a little while for this process to complete and once we logged on not all the services were started so another reboot is …
This tutorial will walk an individual through the steps necessary to configure their installation of BackupExec 2012 to use network shared disk space. Verify that the path to the shared storage is valid and that data can be written to that location:…
This tutorial will show how to configure a new Backup Exec 2012 server and move an existing database to that server with the use of the BEUtility. Install Backup Exec 2012 on the new server and apply all of the latest hotfixes and service packs. The…

695 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