0

I'm looking for an easy batch script that will allow me to delete old files and log what it had delete or not. After searching the web I found "forfiles" really usefull:

forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"

from: Batch file to delete files older than N days

My concern like i said is to log what has been deleted. I tried lots of things but it still doesn't work. Here is my actual code:

set logfile=D:\what\ever\automatic_delete_log_%date:~10,4%-%date:~7,2%-%date:~4,2%_%TIME:~0,2%.%TIME:~3,2%.%TIME:~6,2%.txt
forfiles /p "C:\what\ever\Downloads" /s /m *.* /D -290 /C "cmd /c set status=failed; del @path && set status=success; echo @path @fdate %status% >> %logfile%"
echo %logfile%

The log file is created but is empty, and the old files are not removed. (It should remove the 8 files i have from 2016) When i use the original code it removes the files. I read it might about escaping the &&. I tried to escape them, I tried to escape the ; and i tried to escape both of them without more success. I'm out of idea about what I should do. Can someone help?

The ojectiv is to delete the file, if it succeeds log "path, date, success" otherwise log "path, date, fail".

  • 1
    Remember that && will only run the next command if the previous command was successful (ie. ERRORLEVEL EQU 0). – lit Oct 16 '17 at 18:29
  • 1
    ...and you don't string two lines together with a semicolon – Compo Oct 16 '17 at 20:58

1 Answers1

0

With sufficient escaping, it can be done. Ugly, but can be done. Remember that the DEL command does -not- set ERRORLEVEL. A test for the file's existence would indicate that it has not successfully been deleted.

forfiles /p "C:\src\t" /s /m *.* /D -290 /C ^"cmd.exe /C ^
    set ^"status=failed^" ^&^& ^
    echo DEL @path ^&^& ^
    IF NOT EXIST @path ( ^
        echo @path @fdate SUCCESSFUL >>^"%logfile%^" ^
    ) ELSE ( ^
        echo @path @fdate FAILED >>^"%logfile%^" ^
    ) ^
    ^"
lit
  • 14,456
  • 10
  • 65
  • 119