Question

I am trying to write a script that deletes items in the TEMP folder(s) in Windows 7. I only want it to delete files that are 30 days or older. I'm doing testing in a folder which I have set up in the system's environmental variables as TESTTEMP.

I have the script as follows:

forfiles /p %TESTTEMP% /s /d -30 /c "cmd /c IF @ISDIR==FALSE del @FILE /q"
forfiles /p %TESTTEMP% /s /c "cmd /c IF @ISDIR==TRUE rmdir @FILE"

My logic behind this is that the process should first delete all files within the TESTTEMP directory if the file is older than 30 days, and to check in all the subdirectories. Then I check through the remaining files and if it is an empty directory, remove it.

This script works perfectly - all the files I want to delete are deleted, and those that are supposed to remain, remain. However, I noticed that when I run this batch file, I get the error The system cannot find the file specified. I believe it's having some problem with the rmdir command and not being able to find the directory it just deleted...

Is this something I should be worried about, since the script appears to do what I want it to do? Better yet, is there a way to display which file is not being found so I can try to figure out what's happening on my own?

Thanks for any help!

(For reference, here is the folder structure before and after the batch file is run, assuming all files are older than 30 days:)

Before:

-TestTemp
    -More Test
        testfile1.txt
        testfile2.txt
        testfile3.txt
    testfile1.txt
    testfile2.txt
    testfile3.txt

After:

-TestTemp
Was it helpful?

Solution

You can display files and folders:

forfiles /p "%TESTTEMP%" /s /c "cmd /c IF @ISDIR==TRUE echo rmdir @FILE"
forfiles /p "%TESTTEMP%" /s /d -30 /c "cmd /c IF @ISDIR==FALSE echo del @FILE /q"

OTHER TIPS

If a folder is not empty then it will return a harmless error message. The 2>nul will remove the error message.

forfiles /p %TESTTEMP% /s /c "cmd /c IF @ISDIR==TRUE rmdir @FILE 2>nul"

I was getting this "The system cannot find the file specified" error too, but it went away when I removed the "/s" from the ForFiles call. I did not actually need the /s, but it looks like the poster here did. If you need the recursive delete and can't live with the error (or don't want to swallow it with 2>nul), maybe you could nest a non-recursive ForFiles within a recursive one? Just a thought.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top