Solved

Batch file: delete the oldest files more than 1 week

Posted on 2011-09-20
14
334 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
  • 6
  • 3
  • 3
  • +1
14 Comments
 
LVL 51

Accepted Solution

by:
Bill Prew earned 500 total points
Comment Utility
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 51

Expert Comment

by:Bill Prew
Comment Utility
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
Comment Utility
Are you deleting from a single folder or a tree?
0
 
LVL 51

Expert Comment

by:Bill Prew
Comment Utility
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
Comment Utility
Hi billprew

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

Expert Comment

by:Bill Prew
Comment Utility
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
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:egovernment
Comment Utility
Hi pnorms

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

Expert Comment

by:Qlemo
Comment Utility
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 68

Expert Comment

by:Qlemo
Comment Utility
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 51

Assisted Solution

by:Bill Prew
Bill Prew earned 500 total points
Comment Utility
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 68

Expert Comment

by:Qlemo
Comment Utility
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
Comment Utility
I will check all answers
0
 
LVL 51

Expert Comment

by:Bill Prew
Comment Utility
Any progress?

~bp
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

ADCs have gained traction within the last decade, largely due to increased demand for legacy load balancing appliances to handle more advanced application delivery requirements and improve application performance.
The recent Microsoft changes on update philosophy for Windows pre-10 and their impact on existing WSUS implementations.
This tutorial will walk an individual through the steps necessary to install and configure the Windows Server Backup Utility. Directly connect an external storage device such as a USB drive, or CD\DVD burner: If the device is a USB drive, ensure i…
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…

771 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

12 Experts available now in Live!

Get 1:1 Help Now