I am working on a batch file to read through the files in a folder, and if they are older than 4 days old, move them into an archive\YYYY\MM folder structure. Here’s the code as it stands
::MOVE FILES THAT ARE IN THE ERROR FOLDER TO ARCHIVE ACCORDING TO FILES YEAR AND MONTH
@echo off
set "source=C:\Users\user\Desktop\test"
set "targetRoot=C:\Users\user\Desktop\test\archive"
For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @(
set mm=%%A
set dd=%%B
set yyyy=%%C
)
set currdate=%yyyy%%mm%%dd%
::echo %currdate%
set /a currdate-=7
::echo %currdate%
for %%F in ("%source%\*") do (
for /f "tokens=1,2,3 delims=/ " %%D in ("%%~tF") do (
SET fileDT=%%F%%D%%E
if /I %currdate% GTR %fileDT% (
if not exist "%targetRoot%\%%F" mkdir "%targetRoot%\%%F"
if not exist "%targetRoot%\%%F\%%D" mkdir "%targetRoot%\%%F\%%D"
move "%%~fF" "%targetRoot%\%%F\%%D"
)
)
)
the problem is that after I added the
if /I %currdate% GTR %fileDT%
line, it no longer knows what %%~fF is, and therefore which file to move.
I should note I’m brand new to batch files and I’m mostly modifying code I’ve found online.
The problem is in these two lines:
The first FOR use %%F replaceable parameter, but the second FOR use %%D, %%E and %%F parameters (the %%D is explicit and %%E and %%F are implicit because the TOKENS=1,2,3), so the first meaning of %%F is lost. Just change one of the two FOR parameters, for example:
EDIT: Answer to second question stated in comment.
In this line:
the %currdate% value is constant for all the values in the FOR, but %fileDT% changes with every value in the FOR. In order for this to work, that is, to get the current value of a variable that has changed inside a FOR or IF or parentheses, the Delayed Variable Expansion must be used, that is:
and you must include this line at beginnng of the program: