Tutorial :Batch file which deletes a file which last modification was not today


I just want to know:

How can I delete 'log.txt' if the last modification was not today?

With a batch file.

I'm just talking here about 1 FILE!


You can use forfiles:

forfiles /D -1 /M log.txt /C "cmd /c del @file"  


PowerShell must replace batch.

  if ((dir log.txt).LastWriteTime -lt [datetime]::today) { del log.txt }  


Unfortunately you can't do this in a robust and general way (*).

Powershell, Cygwin, Unix Tools are perfectly good solutions if you can be sure they'll be installed on the target machine.

I wrote a little utility program that takes a path with wildcards and number of days and deletes all files matching the path that are older than the specified number of days. In my environment this was more convenient than installing a 3rd party package.

(*) The following will work for your specific case (modification date not today) as long as the short date format in your regional settings includes the century (i.e. is 10 characters long). But it doesn't generalize for N days, and I don't like relying on the computer's regional settings for this kind of thing:

for %%i in (log.txt) do SET FILETIME=%%~ti  IF NOT "%FILETIME:~0,10%" == "%DATE%" DEL /f log.txt  


Batch makes something that simple very complicated. If you can use Cygwin, or install Unix Tools, consider doing something like this:

find log.txt -mtime +1 -exec rm {} \;  

Found something that might be useful to you using pure batch. You should be able to modify that and adapt it to suit your needs.


For what its worth, you could use either jscript or vbscript. Both of these scripting languages have been installed on MS platforms since the mid 90's

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »