Batch file does delete files. but not work at Windows task schedule

mulsambe 1 Reputation point
2021-12-04T14:11:55.75+00:00

I am running Windows 10.
I have a .bat file aimed at deleting old files.
It contains the following commands :
dir W:
forfiles.exe /P "W:\mydirectory" /s /d -30 /c "cmd /c echo del @mutia keyza "

When I run the .bat file from an Ms-Dos windows, it runs correctly and deletes files.

However, when I run the .bat file from the Task Sheduler :

  • the .bat file does run
  • it shows "dir W:" result
  • it lists the "del xxxx" commands
  • BUT files are not deleted

It seems that other people have asked about the same issue in the past, but I could not find any solution.

Thank you so much for any help.

Windows for business | Windows Client for IT Pros | User experience | Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2021-12-04T14:55:47.123+00:00

    You need to capture both stdout and stderr to see what the .bat file is doing.

    Verify that the scheduled task is set to execute program "cmd.exe".

    In the arguments field set it to:

    /c C:\YourFolderName\YourBatFileName.bat  1>>"C:\YourFolderName\Logs\YourBatFileName-%date:~10,4%-%date:~4,2%%date:~7,2%.log" 2>&1
    

    That will create a daily log file of all executions of the task. The "2>&1" redirects stderr to stdout and ultimately to a single log file.

    0 comments No comments

  2. Limitless Technology 39,921 Reputation points
    2021-12-10T19:43:03.34+00:00

    Hi @mulsambe

    Try giving this a try, you can use this command in a Batch file.

    forfiles /p "PATH" /s /d -30 /c "cmd /c del @file : date >= 30 days >NUL"  
    

    Change "PATH" to the UNC path you are running the command for. This example uses 30 days as the required age but you can adjust this on the above command and use it .

    Hope this resolves your Query!!

    --------
    --If the reply is helpful, please Upvote and Accept it as an answer--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.