Batch file to delete files older than N hours or minutes

Solution 1:

Neither of the solutions here worked for me. They are very innovative solutions, and the first one (.net/FileTimeFilerJS.bat [sic]) actually worked once for me. When I tried to call it on another folder, however, it simply crashed. I tried the second one (jscript/FileTimeFilterJs.bat), but it did not successfully delete all files older than one hour.

My solution requires an executable, but I found it was the best solution for me.

I downloaded FindUtils from GnuWin32, and extracted 3 files (you have to download the two zips below): libintl3.dll, libiconv2.dll, and find.exe (combined they are about 1MB in size). I rename find.exe to gnu_find.exe just to avoid the Windows FIND command.

Then, you can run the beautiful GNU command (below command is for all zip files older than 120 minutes in folder specified by environment variable %fldr%):

gnu_find %fldr% -name *[.:]zip -type f -mmin +120 -delete

Instead of *.zip, I use *[.:]zip, because Windows 7+ will expand the *.zip before find can use it.

Find Utils bin

Find Utils deps

Solution 2:

Its challenging to do this (independent of time date settings) even with WSH\Jscript\VBscript as WSH does not return date object when you request the date/time properties of a file ,but a string that depends on time settings (wmi could be used but this will hit the performance). I suppose you have installed .net framework which make the task far more easier. Here's a hybrid tool that should work in your case. You can save it with whatever name you want. Here's how to use it (its called FileDateFilterJS.bat in this example):

@echo off

for /f "tokens=* delims=" %%# in ('FileDateFilterJS.bat  "." -hh -5') do (
    echo deleting  "%%~f#"
    echo del /q /f "%%~f#"
)

pause

Where the hours are 5 - -hh -5 and directory is current - "." .You can remove the echo before del command.

This script took me far more time than I've expected (despite I've researched the topic and has some parts ready) and is no so heavy tested so probably is still not buggy-free.And I suppose the help message and options could be improved.

Solution 3:

@echo off
cd /d "your file path"
:: delete files 3 hours ago. If you want other condition, refer https://www.w3schools.com/asp/func_dateadd.asp
echo wscript.echo dateadd("h",-3,now())>GetOldDate.vbs
for /f "tokens=1,2 delims= " %%i in ('cscript /nologo GetOldDate.vbs') do (
  set d=%%i
  set t=%%j
)
echo "%d%"
echo "%t%"
for /f "tokens=1,2,3 delims=/" %%a in ("%d%") do (
  set y=%%a
  set m=%%b
  set d=%%c
)
for /f "tokens=1,2,3 delims=:" %%a in ("%t%") do (
  set h=%%a
  set mm=%%b
  set s=%%c
)

if %m% LSS 10 set m=0%m%
if %d% LSS 10 set d=0%d%
if %h% LSS 10 set h=0%h%
if %mm% LSS 10 set mm=0%mm%

set OldDate=%y%/%m%/%d% %h%:%mm%
echo "%OldDate%"
del GetOldDate.vbs
for %%a in (*) do ( 
  if "%%~ta" lss "%OldDate%" (
    echo %%a
    echo "%%~ta"
    del %%a
  )
)