Thursday, September 17, 2009

Misusing ROBOCOPY to delete old files

We have a lot of servers that store files that are not needed after some time (for example, Logfiles). Usually these files are sometimes needed for some days but not after that.

Therefore I needed a fast and quick way to delete old files. I found some programs that are able to do so, but I wanted a really simple solution.

After some testing, I decided to “misuse” Robocopy for that. Actually, Robocopy has no option to delete old files but it has the strange option “/CREATE”. This option will copy all files but with 0 bytes, so the copy is very fast.

The Batchfile that does the real work (DeleteOldFiles_Exec.bat) looks like this:


SET SRC=%1
SET PATRN=%2
SET DAYS=%3
IF NOT EXIST C:\TEMP\. md C:\TEMP
IF NOT EXIST C:\TEMP\TRASH\. md C:\TEMP\trash
%~dp0robocopy %SRC% "C:\TEMP\TRASH" %PATRN% /R:1 /s /mov /create /XA:A /minage:%days%
Rem /L for List only
rd C:\TEMP\TRASH /s /q


It will move the given files (%PATRN%) from the source folder (%SRC%) that are older than the given days (%DAYS%). The options for Robocopy are pretty easy except the /CREATE option (see above) and the /XA:A option which excludes all files with the ARCHIVE attribute set. This option is set since I do not want to delete any file that hasn't been backed up.

I then call this batch like this:

CALL deleteoldfiles_exec "C:\Temp" *.* 10

This will delete all files (*.*) in the directory C:\Temp that are older than 10 days.

5 comments:

  1. Quite an ingenius use of the /CREATE switch.

    Robocopy actually copies the file (no surprise there!) rather than amend the FAT as a simple windows cut/paste job would do, so a very smart workaround.

    Thanks
    Pops

    ReplyDelete
    Replies
    1. Seems like copying the file (even if is 0 byte size) would be slower than simply amending to the FAT, so why would this be better than copy/past?

      Delete
  2. very cool, Michael! thanks for sharing!

    just a side note, great and free little tool SpaceSniffer will help to identify all folders you need to clean up using your script. So two of them will work nicely.

    ReplyDelete
  3. This is simple and very useful., this is the real case of "misusing" robocopy :D Thanks for sharing this..

    ReplyDelete
  4. i got a the better solution for this. i wish i can help other people and givev the easier and faster path to move on next level. You guys can try DuplicatesDeleter program instead. It's more easy and faster to use. So we can save our time to make other job. happy to share it with you guys. :)

    ReplyDelete