0

I want to delete files older than certain number of days, based on their names' pattern, using a batch script. I also want to check beforehand, whether the files exist or not. I'm using the following code:

if exist "C:\Users\John\Documents\Week*" 
(
forfiles /D -30 /C "cmd /c del C:\Users\John\Documents\Week*"
) 
else (exit)

However nothing is happening.

halfer
  • 19,824
  • 17
  • 99
  • 186
John
  • 3
  • 1
  • just try with `del /q "C:\Users\John\Documents\Week*" 2>nul` – npocmaka Aug 26 '15 at 11:02
  • forfiles /d -30 /c "something" with do the same "something" for each file older than 30 days. In your case if C:\Users\John\Documents\Week* matches anything ALL of them will be deleted once for every file in the current directory that is older than 30 days - if there are 10 files in the current directory older than 30 days you are deleting ALL files matching C:\Users\John\Documents\Week* 10 times. – Jerry Jeremiah Aug 26 '15 at 11:08
  • 2
    @npocmaka unless I am completely wrong he doesn't want to delete all files matching that pattern - just the ones that are older than 30 days. – Jerry Jeremiah Aug 26 '15 at 11:09
  • Maybe [this](http://stackoverflow.com/a/25073859/2861476) could help – MC ND Aug 26 '15 at 11:40
  • As pointed out by @MCND the parenthesis indentation was wrong. After correcting it the script ran. However, all files resembling the pattern Week* are getting deleted. – John Aug 26 '15 at 16:54
  • @JerryJeremiah Am new to batch scripting. Can you please explain your suggestion? – John Aug 26 '15 at 16:57

1 Answers1

1

Your code is executing the del with a mask that includes all the matching files. You need to let forfiles to search the files and execute the deletion for each of them.

You can try with something like

if exist "C:\Users\John\Documents\Week*" (
    forfiles /D -30 /P "C:\Users\John\Documents" /M "Week*" /C "cmd /c del @PATH"
) else ( exit )
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • It worked. But had to remove the quotes from the path. Thanks @MCND – John Aug 27 '15 at 11:21
  • @John, sorry, I included an ending backslash in the path that should not be present (it is escaping the quote). Removed. – MC ND Aug 27 '15 at 12:18