1

I'm trying to write a script in batch file that do the following:

  1. Locate all folders with the name "Mdata" in "C:\Project".
  2. Delete all folders in "Mdata" that older than 30 days.

My code is:

@echo off
for  /f "delims=" %%a in ('dir /b /s /a:d "C:\project\" ^|findstr /e /i "\Mdata"') do (
@echo "%%~a"
setlocal
set target=%%a
set days=-30
for /f "usebackq delims=" %%G in (
  `forfiles /p "%target%" /c "cmd /c if /i @isdir == true echo @path" /d %days% 2^>nul`
  ) do rd /s /q "%%~G"
  endlocal & exit /b
)
pause

The first task to locate all "Mdata" folders working well. but the delete dosen't work.

YWATFA
  • 91
  • 1
  • 2
  • 9
  • possible duplicate of [Batch file to delete files older than N days](http://stackoverflow.com/questions/51054/batch-file-to-delete-files-older-than-n-days) – Joe Feb 01 '15 at 13:55

1 Answers1

1

This should take care of it. I simplified your script a bit to remove the inner FOR loop since you can just perform your deletion from withing the FORFILES command.

@echo off
SETLOCAL

set days=-30
for /f "delims=" %%a in ('dir /b /s /a:d "C:\project\" ^|findstr /e /i "\Mdata"') do (
    echo "%%~a" 
    forfiles /p "%%~a" /d %days% /c "cmd /c if /i @isdir==true echo @path & rd /s /q @path"
)

ENDLOCAL
pause

The reason your script wasn't working is because you did not have delayed expansion enabled, so the target and days would not be usable for your inner FOR loop. As it stands though, you don't need this functionality enabled for what you are trying to accomplish.

Jason Faulkner
  • 6,378
  • 2
  • 28
  • 33
  • Thanks a lot it is working good. Now I'm trying to send the path (String) of all directories prior delete to Excel file: Does it work if I add: 'echo @path>>path_Deleted.xls' in the 'forfiles' loop. @Jason Faulkner. – YWATFA Feb 01 '15 at 18:03
  • The issue is : it send to Excel the "Mdata" Folders and not the deleted folders string! Where should I put the 'echo "%%~a">>path_Deleted.xls' inorder to see the deleted folders name? @Jason Faulkner. – YWATFA Feb 01 '15 at 19:00
  • @YWATFA - Excel is a binary format so you won't be able to send the output directly to XLS format. – Jason Faulkner Feb 02 '15 at 14:01