Solved

Batch file to Delete files older than x hours

Posted on 2003-11-28
13
43,029 Views
Last Modified: 2011-08-18
To the brain-boffins out there:
I need to delete all .pdf in a folder older than 24h, but I don't know much about batch files. I'll probably run it via a scheduled task.
Thanx for your expert advice.
sl
0
Comment
Question by:Sterna
  • 4
  • 2
  • 2
  • +4
13 Comments
 
LVL 16

Expert Comment

by:_nn_
Comment Utility
0
 
LVL 2

Expert Comment

by:MiniMaxXPC
Comment Utility
How about this?

@       echo off


rem     +====================================================================
rem     | This package needs the new CMD.EXE extensions to be loaded and
rem     | will refuse to run, if they can not be enabled.
rem     +====================================================================

        verify other 2>NUL
        setLocal enableExtensions
        if errorLevel 1 (
            echo.
            echo *ERROR*
            echo.
            echo Sorry - this program requires that extensions to CMD.EXE are
            echo enabled.  Please consult your manual for instruction on how
            echo to proceed.

            goto :EOF
        )

        set delcount=0

rem     Use the DIR command to get a simple listing of file names sorted by date.
rem     The file Timestamp.log marks the time when this script was last run.
rem     Assuming that this was at least 24 hours ago, any files that is sorted
rem     *before* the timestamp is safe to delete.  When the timestamp file is
rem     encountered, we are done.

        for /f "delims=" %%f in ('dir /b /o:d') do (

            if /i "%%f" == "Timestamp.log" goto :done
            if /i "%%~xf" == ".PDF" call :delete "%%f"
        )
:done

rem     Update the Timestamp.log file.  The update 'moves' the log file
rem     ahead in the list of files sorted by date.  Any PDF file modified
rem     after the new timestamp will thus not be deleted the next the
rem     del_marked script is run.

        echo %date% %time% - deleted %delcount% files >> "Timestamp.log"
        echo %date% %time% - deleted %delcount% files
        goto :EOF

:delete
        set /a delcount=delcount + 1
        del "%~1"
        goto :EOF

--
MiniMax
0
 
LVL 10

Accepted Solution

by:
pbarrette earned 250 total points
Comment Utility
Hi Sterna,

I have 2 solutions you can use for NT/2K/XP.

The first will delete all files older than the specified number of minutes:

:: ---------------EXAMPLE.BAT-----------------
@ECHO OFF
:: ------------
:: This is where you set the number
:: of minutes you want subtracted
:: from the current date/time.
:: ------------
SET MyMins=1440


:: ------------
:: Get current date/time
:: ------------
FOR /F "TOKENS=2-4 DELIMS=/ " %%F IN ('DATE /T') DO (
 SET YYYY=%%H
 SET MM=%%F
 SET DD=%%G
)
FOR /F "TOKENS=5-6 DELIMS=: " %%F IN ('ECHO.^|TIME') DO (
 SET HR=%%F
 SET MN=%%G
)

IF %DD% LSS 10 (SET DD=%DD:~1%)
IF %MM% LSS 10 (SET MM=%MM:~1%)
IF %HR% LSS 10 (SET HR=%HR:~1%)
IF %MN% LSS 10 (SET MN=%MN:~1%)

: ------------
:: Subtract minutes from current time.
:: ------------
SET /A MN=%MN% - %MyMins%

:: ------------
:: Do the massively painful
:: reverse calculations.. :(
:: ------------
:LoopMins
IF /I %MN% GEQ 0 (GOTO LoopHrs)
SET /A MN=%MN% + 60
SET /A HR=%HR% - 1
GOTO LoopMins
:LoopHrs
IF /I %HR% GTR 0 (GOTO LoopDate)
SET /A HR=%HR% + 23
SET /A DD=%DD% - 1
GOTO LoopHrs
:LoopDate
IF /I %DD% GTR 0 (GOTO DONE)
set /A mm=%mm% - 1
if /I %mm% GTR 0 goto ADJUSTDAY
set /A mm=12
set /A yyyy=%yyyy% - 1
:ADJUSTDAY
if %mm%==1 goto SET31
if %mm%==2 goto LEAPCHK
if %mm%==3 goto SET31
if %mm%==4 goto SET30
if %mm%==5 goto SET31
if %mm%==6 goto SET30
if %mm%==7 goto SET31
if %mm%==8 goto SET31
if %mm%==9 goto SET30
if %mm%==10 goto SET31
if %mm%==11 goto SET30
if %mm%==12 goto SET31
goto ERROR
:SET31
set /A dd=31 + %dd%
goto LoopDate
:SET30
set /A dd=30 + %dd%
goto LoopDate
:LEAPCHK
set /A tt=%yyyy% %% 4
if not %tt%==0 goto SET28
set /A tt=%yyyy% %% 100
if not %tt%==0 goto SET29
set /A tt=%yyyy% %% 400
if %tt%==0 goto SET29
:SET28
set /A dd=28 + %dd%
goto LoopDate
:SET29
set /A dd=29 + %dd%
goto LoopDate
:DONE
IF %dd% LSS 10 set dd=0%dd%
IF %mm% LSS 10 set mm=0%mm%
IF %HR% LSS 10 SET HR=0%HR%
IF %MN% LSS 10 SET MN=0%MN%


for %%i in (*.*) do (
 set FileName=%%i
 SET FTIME=%%~ti
 CALL :PROCESSFILE
)

set mm=
set yyyy=
set dd=
set thedate=
goto :EOF

:PROCESSFILE
set fyyyy=%FTIME:~6,4%
set fmm=%FTIME:~0,2%
set fdd=%FTIME:~3,2%
SET fhr=%FTIME:~11,2%
SET fmn=%FTIME:~14,2%

if /I %fyyyy% GTR 2069 set fyyyy=19%FTIME:~6,2%

:: --------
:: Deal with File times
:: reported as AM/PM vs.
:: calculated times as 24hr.
:: --------
IF /I "%FTIME:~17,1%" == "P" (
 IF %fhr% LSS 10 (
  SET /A fhr=%fhr:~1,1% + 12
 ) ELSE (
  IF %fhr% LEQ 11 (
   SET /A fhr=%fhr% + 12
  )
 )
)
IF /I "%FTIME:~17,1%" == "A" (
 IF %fhr%==12 (
  SET fhr=00
 )
)

:: +*************************************+
:: | This is where the files are deleted |
:: | Change the ECHO command to DEL to   |
:: | delete. ECHO is used for test.      |
:: +*************************************+
if /I %yyyy%%mm%%dd% GEQ %fyyyy%%fmm%%fdd% (
 IF /I 1%hr%%mn% GEQ 1%fhr%%fmn% (

  ECHO %FileName%

 )
)
ECHO Calcdate=%yyyy%%mm%%dd%%hr%%mn%

set temp=
set fyyyy=
set fmm=
set fdd=

:EXIT
:: ----------END-EXAMPLE.BAT-------------

Or, you can use the old standby that calculates dates:

:: --------DELOLD.BAT----------
@ECHO OFF
SET OLDERTHAN=%1
IF NOT DEFINED OLDERTHAN (GOTO SYNTAX)

for /f "tokens=2" %%i in ('date /t') do set thedate=%%i

set mm=%thedate:~0,2%
set dd=%thedate:~3,2%
set yyyy=%thedate:~6,4%

set /A dd=%dd% - %OLDERTHAN%
set /A mm=%mm% + 0

:LoopDate
if /I %dd% GTR 0 goto DONE
set /A mm=%mm% - 1
if /I %mm% GTR 0 goto ADJUSTDAY
set /A mm=12
set /A yyyy=%yyyy% - 1

:ADJUSTDAY
if %mm%==1 goto SET31
if %mm%==2 goto LEAPCHK
if %mm%==3 goto SET31
if %mm%==4 goto SET30
if %mm%==5 goto SET31
if %mm%==6 goto SET30
if %mm%==7 goto SET31
if %mm%==8 goto SET31
if %mm%==9 goto SET30
if %mm%==10 goto SET31
if %mm%==11 goto SET30
if %mm%==12 goto SET31

goto ERROR

:SET31
set /A dd=31 + %dd%
goto LoopDate

:SET30
set /A dd=30 + %dd%
goto LoopDate

:LEAPCHK
set /A tt=%yyyy% %% 4
if not %tt%==0 goto SET28
set /A tt=%yyyy% %% 100
if not %tt%==0 goto SET29
set /A tt=%yyyy% %% 400
if %tt%==0 goto SET29

:SET28
set /A dd=28 + %dd%
goto LoopDate

:SET29
set /A dd=29 + %dd%
goto LoopDate

:DONE
if /i %dd% LSS 10 set dd=0%dd%
if /I %mm% LSS 10 set mm=0%mm%
for %%i in (*.*) do (
set FileName=%%i
call :PROCESSFILE %%~ti
)

set mm=
set yyyy=
set dd=
set thedate=
goto EXIT

:SYNTAX
ECHO.
ECHO USAGE:
ECHO DELOLD X
ECHO   Where X is the number of days previous to Today.
ECHO.
ECHO EX: "DELOLD 5" Deletes files older than 5 days.
GOTO EXIT

:PROCESSFILE
set temp=%1
set fyyyy=20%temp:~6%
set fmm=%temp:~0,2%
set fdd=%temp:~3,2%
if /I %fyyyy% GTR 2069 set fyyyy=19%temp:~6%

:: +*************************************+
:: | This is where the files are deleted |
:: | Change the ECHO command to DEL to   |
:: | delete. ECHO is used for test.      |
:: +*************************************+
if /I %yyyy%%mm%%dd% GEQ %fyyyy%%fmm%%fdd% (
ECHO %FileName%
)

set temp=
set fyyyy=
set fmm=
set fdd=

:EXIT
:: ----------END-DELOLD.BAT-------------

Replace ECHO with DEL in the specified location to make the batchfile do its job. It currently just displays the file that will be deleted so you can test without actually deleting the file.

The batchfile acts upon the current directory, so if you are calling this batchfile from an automated system, you may want to add a "CD X:\Path" to the top of the file.


Hope this helps. If you need any help or explanations of these batch files, feel free to ask.

pb
0
 
LVL 2

Expert Comment

by:MiniMaxXPC
Comment Utility
Yeah, I think I sort of answered it, but without feedback from the originator, it is hard to tell if the solution fits the problem 100%. Same goes for expert 'pbarrette' I think.
--
MiniMax
0
 
LVL 10

Expert Comment

by:pbarrette
Comment Utility
Hi Pasha,

I'll put my hand up on this one as well. The old "Delete my files after X many Y's" question...

pb
0
 

Author Comment

by:Sterna
Comment Utility
I'd like to finalize this Question! Sorry I took so long ~ had to work on another project in the meanwhile. Still haven't implemented the code, but it seems perfect. Thank you MiniMaxXPC! Your help much appreciated.
Happy Programming.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 10

Expert Comment

by:pbarrette
Comment Utility
Hi Sterna,

If you have recieved a working answer, you should close out this question yourself by accepting a comment as an answer and assigning it a grade value.

Remember that the grade you assign does not change the amount of points that you spent on the question. Instead, it changes the amount of points that the expert recieves for answering it. So please be generous to MiniMax.

Thanks,
pb
0
 
LVL 4

Expert Comment

by:onlyamir007
Comment Utility
Hi

I have same kind of problem I need 2 copy all files & folders modified not all to other network  computer I already shared that directory where I want put files and folders  but I need to Schedule  I want this batch file run  daily 11:30 pm evening  .

Muhammad Amir
0
 
LVL 10

Expert Comment

by:pbarrette
Comment Utility
Hi Amir,

To schedule the batch file, you will need to use the "Scheduling Service". Look at "Control Panel"->"Scheduled Tasks" and add a new scheduled task. Since you will be sending it over the network, you will need to run the task as a user who has access to the network shares. Then you will need to modify the batchfile to either map the network drive, or specify the UNC to the shared folder.

Like this:
COPY "%FileName%" "\\Computer\Share\%FileName%"

pb
0
 
LVL 4

Expert Comment

by:onlyamir007
Comment Utility
thank you very much pbarrette! 4 your quick reply

http://www.clickamir.com/forum.cfm
0
 

Expert Comment

by:dservin
Comment Utility
For the 1st code example, the delete after X minutes was great.  But there seemed to be a bug when just after midnight.   If  the time is 1AM, and I delete 30 minutes, I should get the same day but the HHMN would be 0030 for the time portion of the calcdate variable.  It always seemd to be off by 1 hour, therefore by 1 whole day+hour when you were close to midnight.   I changed the :LoopHrs and :LoopDate as follows.  Thanks a heap pbarrette for the code, I still couldn't have got this far without your help.



:LoopHrs

IF /I %HR% GTR 0 (GOTO LoopDate)

SET /A HR=%HR% + 24      :: Changed from 23

SET /A DD=%DD% - 1

  

GOTO LoopHrs

:LoopDate

SET /A HR=%HR%

:: Added next  4 lines

IF /I %HR% EQU 24 (

  SET /A HR=0       :: If at 24 hours set to 00 for midnight

  SET /A DD=%DD%+1  :: Add the day back that was previously subtracted.

)

IF /I %DD% GTR 0 (GOTO DONE)

set /A mm=%mm% - 1

if /I %mm% GTR 0 goto ADJUSTDAY

set /A mm=12

set /A yyyy=%yyyy% - 1

Open in new window

0
 

Expert Comment

by:skataria
Comment Utility
has anyone tried

FORFILES /P C:\DIRECTORY\SUB-DIRECTORY\  /S /M *.* /D -1 /C "CMD /C DEL @FILE"


This works for me like a charm and deletes all files in the sub-directories and all sub-sub directories older than 1 day. Look up the dos help for this command
FORFILES /?

HTH..

Sandeep

0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
TOMORROW TOMORROW.BAT is inspired by a question I get asked over and over again; that is, "How can I use batch file commands to obtain tomorrow's date?" The crux of this batch file revolves around the XCOPY command - a technique I discovered w…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

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

11 Experts available now in Live!

Get 1:1 Help Now