0

Variable declarations:

SET /A days=180
SET /A count=0
SET cmdStr=CMD /C DEL @FILE
SET xmlDir=D:\Client Communications\XML

I already have a working for loop to that uses FORFILES to delete xml and psr data files and it looks like this:

FOR %%G IN (.xml, .psr) DO (
    FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "%cmdStr%" >nul 2>nul
    IF ERRORLEVEL 1 (
        ECHO No %%G files %days% days old or older were found.
    ) ELSE (
        ECHO %%G files as old as %days% days or older have been deleted.
    )
)

Now I want to modify this batch file to also count the amount of files (for each file type) that are removed by the FORFILES command, which I believe can be achieved by putting the FORFILES command into a FOR /F loop. I didn't want to do a nested for loop, but so ended up creating a subroutine. My code now looks like this:

FOR %%G IN (.xml, .psr) DO (
    CALL :process_files %%G count
    IF !count!==0 (
        ECHO No %%G files %days% days old or older were found.
    ) ELSE (
        ECHO !count! %%G files as old as %days% days or older have been deleted.
    )
    SET !count!=0
)

PAUSE
ENDLOCAL

:process_files
FOR /F "delims=" %%G IN ('
    FORFILES /P "%xmlDir%" /M *%1 /D -%days% /C "%cmdStr%"
') DO SET /A %~2+=1
EXIT /B

It doesn't seem that count is being incremented properly. When I try to echo !count! it outputs:

!count! .xml files as old as 180 days or older have been deleted.

When I try to change !count! to %count% I get this output:

No .psr files 180 days old or older were found.

If I echo count inside of :process_files just before it ends it outputs "count", so it looks like it's being treated as a string, not an integer. Not sure why that is.

Tom
  • 291
  • 2
  • 12
  • 1
    Is [delayed expansion](https://ss64.com/nt/delayedexpansion.html) enabled at top of the batch file? Don't do that because in this case files with one or more exclamation marks in name would not be processed correct. Instead use `setlocal EnableDelayedExpansion` immediately above `IF !count!==0 (` and use after the __IF__ condition `endlocal`. Additionally you have to change `SET !count!=0` to `SET count=0` to reset the value of this environment variable to 0 before calling `process_files` a second time for files with file extension `.psr`. – Mofi May 28 '19 at 17:16
  • 1
    And you need `goto :EOF` or `exit /B` __above__ the label line `:process_files` to avoid a fall through in batch file execution to subroutine once the main __FOR__ loop finished. For more details see [Where does GOTO :EOF return to?](https://stackoverflow.com/a/37518000/3074564) Further I recommend to use in subroutine `process_files` the __FOR__ loop with `"eol=| delims="` instead of just `"delims="` to define vertical bar instead of semicolon as end of line character. No file/folder name can begin with `|`, but they can begin with `;`. – Mofi May 28 '19 at 17:19
  • Thank you, it is working perfectly now. – Tom May 28 '19 at 17:27

0 Answers0