简体   繁体   中英

Batch Script to delete files past 5 days old

I have a batch script that I have run through Task Scheduler every night at midnight. Here is the script:

forfiles /M *.bak /p "Z:\Logs" /S /D -5 /C "cmd /c del @file : date >= 5 days >NUL"

But when the task runs at midnight, it does not delete the files older than 5 days. If I double click on the batch file and run it manually, it does delete the files older than 5 days. What is wrong or do I need to do something different to make this work?

EDIT:

Here is my full batch file and more information about the task schedule:

sqlcmd -S server\SQLEXPRESS -U user -P password -i "D:\BackupPrograms\translogsbackup.sql"
forfiles /M *.trn /p "Z:\Logs" /S /D -5 /C "cmd /c del @file >NUL"

I am using an administrator account for the task schedule to run every night. I am trying to get it to delete the older backups that the sqlcmd is creating, that way I make sure I am not wasting a bunch of space on Full SQL backups that are not needed. I hope this helps more. I am just confused why the batch file would act differently running through the Task Scheduler and when I double click on it to run.

It doesn't work from the command prompt any more than it does from the scheduler, and here's why.

/C "cmd /c del @file : date >= 5 days>NUL"

The : is illegal at that position in a command line, and it's ignored.

The >= is interpreted as the output redirection symbol, and therefore all of the output is redirected to a file named 5 in the current directory.

You can test this at a command prompt yourself:

  1. Create a new, empty folder on your system, such as C:\\Test , from a command prompt, and make it the active directory.

     C:\\>md Test C:\\>cd Test 
  2. Create a couple of dummy files in the folder:

     C:\\Test>echo file1 > file1.txt C:\\Test> C:\\Test>echo file2 > file2.txt 
  3. Do a directory to see what's there:

     C:\\Test>dir /b file1.txt file2.txt C:\\Test> 
  4. Try this forfiles command to see the output:

     C:\\Test>forfiles /M *.txt /C "cmd /c echo @file" "file1.txt" "file2.txt" C:\\Test> 
  5. Change the forfiles to add the : date >= 5 days and run again:

     C:\\Test>forfiles /M *.txt /C "cmd /c echo @file : date >= 5 days" C:\\Test> 
  6. Do a directory to see what's there:

     C:\\Test>dir /b 5 file1.txt file2.txt C:\\Test> 

Note the new file with the name 5 .

So the solution: Delete the : date >= 5 days . You can leave the NUL portion, as that legitimately redirects any output to NUL (nothing) so that it's not displayed. So your command would look like this:

forfiles /M *.bak /p "Z:\Logs" /S /D -5 /C "cmd /c del @file >NUL"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM