How to delete files based on date?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
yalgaar
Posts: 4
Joined: 09 Oct 2008 15:44

How to delete files based on date?

#1 Post by yalgaar » 04 Dec 2008 12:03

Is there a way to delete all files if they are older than certain date?

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

#2 Post by DosItHelp » 11 Dec 2008 00:33

yalgaar,

You can use XCOPY /L /D:m-d-y file file to identify files for deletion by date. I.e. to show all files older than 12-8-08 use:

Code: Select all

for %A in (*.*) do @xcopy /D:12-8-08 /L "%~fA" "%~fA" >NUL 2>NUL &&echo.DEL "%~A"


/L Displays files that would be copied.
/D:m-d-y Copies files changed on or after the specified date.

The trick is:
If the file is older than the given date then the XCOPY will succeed without trying to copy the file.
If the file date is equal or newer than the given date than the XCOPY command will attempt to copy the file, which will fail because it can't copy the file onto itself.
The && makes sure echo.DEL "%A" is only executed when XCOPY succeeds, i.e. the file was older.
The /L option makes sure that XCOPY only checks but doesn't actually attempt to copy any file.

DosItHelp? :wink:

wsorich
Posts: 1
Joined: 14 Dec 2008 23:01

#3 Post by wsorich » 14 Dec 2008 23:19

DosItHelp, this is really awesome, but I am having a couple issues trying to use this cool script.

1- When I enter the script from the command line, within the directory that the files I want to selectively remove, the script seems to identifiy the correct file....

C:\Ziptemp\Files>for %A in (*.*) do @xcopy /D:11-20-08 /L "%~fA" "%~fA" >NUL 2>N
UL &&echo.DEL "%~A"
DEL "wrar38b2.exe"


But the file [wrar38b2.exe] itself is not deleted...
So the first question would be, are you generating a series of commands that need to be called later?.. or is the script supposed to call the del command itself?...

2- If I try to use this script in a batch file, it fails with...

C:\Ziptemp>testdel.bat
C:\Ziptemp>cd "c:\ziptemp\files"
The following usage of the path operator in batch-parameter
substitution is invalid: %~fA" "%~fA" >NUL 2>NUL &&echo.DEL "%~A"

For valid formats type CALL /? or FOR /?
The syntax of the command is incorrect.
C:\Ziptemp\Files>for 11-20-08 /L "o @xcopy /D:11-20-08 /L "%~fA" "%~fA" >NUL 2>N
UL &&echo.DEL "%~A"


So the second question is, can you please assit in telling me what needs to occur for the script to run in a batch file..
Thanks in advance, Wally.

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

#4 Post by DosItHelp » 15 Dec 2008 21:10

Wally,

1. To actually delete the files remove the "echo."
2. To use in batch use "%%A" instead of "%A" for the variable.
for %%A in (*.*) do @xcopy /D:12-8-08 /L "%%~fA" "%%~fA" >NUL 2>NUL &&echo.DEL "%%~A"

DosItHelp? :wink:

Post Reply