You have other problems besides recursion stack limits. The IF statement does not know how to compare dates. It only knows strings and numbers. In order to properly compare dates you must reformat the date to be in YYYYMMDD format.
Your timestamp information for use in the output file name should be collected all at once. Your existing code gets the hour at the beginning of the process, and the date, minutes and seconds at the end of the process. Not good. There could be a significant time gap between the start and end times.
Batch has two types of recursion errors:
1) Only 31 SETLOCAL levels within one CALL level.
2) A variable number of recursive CALLs allowed, depending on Windows version, machine memory, ...
There is no way to increase the size of the stack. If you get a recursion error, you must look for ways to reduce the amount of recursion. In your case, you can simply let FOR /R do all the recursion for you!
I modified the script such that the list of files is generated if a 4th argument is passed. I also incorporated the timestamp into file list file name.
The code assumes your machine's file date/time value starts with MM/DD/YYYY. The code will have to be modified if it does not.
@echo off
setlocal enableDelayedExpansion
REM This program takes three parameters <starting directory> <startdate> <enddate>
REM The startdate and endate should be in format: mm/dd/yyyy
REM The program will recursively look through all directories and sub-directories
REM from the given <starting directory> and count up the number of files written
REM within the date range from <startdate> until <endate>
REM It will then write out a RetentionReport_<date>_<time>.txt file that lists
REM one line showing the <startdate> <enddate> and the # of files found.
REM If you don't pass in all three arguments it will let you know and then exit.
REM You need to set your TESTDIR below to a hardpath location for the writing
REM of the Reports
REM If you want to print out a .tmp file that lists the files counted for the
REM period given then you can pass in a 4th argument with any value
if "%~3" == "" (
echo Please pass in arguments for starting directory, startdate, and enddate.
echo startdate and endate should be in the format mm/dd/yyyy
exit/b
)
set "TAB= "
set "TESTDIR=D:\TEST\"
set "startdate=%~2"
set "start=%startdate:~-4%%startdate:~0,2%%startdate:~3,2%"
set "enddate=%~3"
set "end=%enddate:~-4%%enddate:~0,2%%enddate:~3,2%"
set "timestamp=%date:~-4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%"
set "timestamp=%timestamp: =0%"
for /r "%~1" %%F in (*) do (
set "dt=%%~tF"
set "dt=!dt:~6,4!!dt:~0,2!!dt:~3,2!"
if !dt! geq %start% if !dt! leq %end% (
if "%~4" neq "" (echo %%~tF %%F) >>"%TESTDIR%MONTH_files_%timestamp%.tmp"
set /a cnt+=1
)
)
(echo %startdate%%TAB%%enddate%%TAB%%cnt%) >>"%testdir%RetentionReport_%timestamp%.txt"