Search code examples
windowsbatch-filescheduled-tasksdelete-fileforfiles

When I put a batch program in the task scheduler, it didn't finish the whole task, so why did this happen?


This problem is from the scheduler task, batch program, or the files in a folder that I want to delete it using the batch program? and this is the batch program:

forfiles /p "D:\nameOfFolder" /s /m *.* /d -7 /c "cmd /c del @path"

Solution

  • Replace /M *.* by /M * to even include files without extension, because forfiles treats wildcards differently than most other commands. /M * may even be omitted since this is the default setting anyway.

    Regard that forfiles iterates both files and directories, so you need to exclude the latter, because del may try to delete its contents then. Therefore, implement a condition based on the forfiles-specific variable @isdir.

    forfiles /S /P "D:\nameOfFolder" /M * /D -7 /C "cmd /D /C if @isdir==FALSE del @path"
    

    As a side note, never append a trailing backslash to a (quoted) path, because something like /P "D:\" would let the command fail since \" constitutes an escaped quotation mark for forfiles, ruining the command line. You may however specify /P "D:\.".