Solved

Batch file to Delete files older than x hours

Posted on 2003-11-28
13
43,617 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
[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
  • 4
  • 2
  • 2
  • +4
13 Comments
 
LVL 16

Expert Comment

by:_nn_
ID: 9838148
0
 
LVL 2

Expert Comment

by:MiniMaxXPC
ID: 9840585
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
ID: 9876879
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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 2

Expert Comment

by:MiniMaxXPC
ID: 10090358
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
ID: 10127032
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
ID: 10127454
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
 
LVL 10

Expert Comment

by:pbarrette
ID: 10127474
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
ID: 10302889
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
ID: 10303477
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
ID: 10307503
thank you very much pbarrette! 4 your quick reply

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

Expert Comment

by:dservin
ID: 21490794
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
ID: 24639833
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

YESTERDAY YESTERDAY.BAT is inspired by a previous article I wrote entitled: TOMORROW.BAT (http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/MS_DOS/A_4196-Advanced-Batch-File-Programming-TOMORROW-BAT.html). The crux of this batch f…
Introduction: Recently, I got a requirement to zip all files individually with batch file script in Windows OS. I don't know much about scripting, but I searched Google and found a lot of examples and websites to complete my task. Finally, I was ab…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

688 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