Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Batch file: delete the oldest files more than 1 week

Posted on 2011-09-20
14
Medium Priority
?
410 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 59

Accepted Solution

by:
Bill Prew earned 2000 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 59

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
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

 
LVL 59

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 59

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 72

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 72

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 59

Assisted Solution

by:Bill Prew
Bill Prew earned 2000 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 72

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 59

Expert Comment

by:Bill Prew
ID: 37180624
Any progress?

~bp
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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…
You might have come across a situation when you have Exchange 2013 server in two different sites (Production and DR). After adding the Database copy in ECP console it displays Database copy status unknown for the DR exchange server. Issue is strange…
This tutorial will walk an individual through the steps necessary to enable the VMware\Hyper-V licensed feature of Backup Exec 2012. In addition, how to add a VMware server and configure a backup job. The first step is to acquire the necessary licen…
This tutorial will show how to configure a single USB drive with a separate folder for each day of the week. This will allow each of the backups to be kept separate preventing the previous day’s backup from being overwritten. The USB drive must be s…

581 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