Reputation: 13
I have the following code (which works well) in a batch file for listing directories recursively with a filecount for each directory, but besides what I already have, I need to know the date of the oldest file in current directory, where it says I_NEED_YEAR_HERE
, how can I do that?
@echo off setlocal disableDelayedExpansion if "%~1"=="" (call :recurse ".") else call :recurse %1 exit /b :recurse setlocal set fileCnt=0 for /d %%D in ("%~1\*") do call :recurse "%%~fD" for /f %%F in ('dir /b /a-d "%~1\*" 2^>nul ^| find /v /c ""') do ( set /a fileCnt+=%%F ) echo %~f1 has %fileCnt% files and the oldest file is from year I_NEED_YEAR_HERE ( endlocal set /a fileCnt+=%fileCnt% ) exit /b
Upvotes: 1
Views: 2073
Reputation: 9545
With your code you'll have to add a new FOR
loop and enable the Delayedexpansion
Something like that will work :
@echo off
setlocal enableDelayedExpansion
if "%~1"=="" (call :recurse ".") else call :recurse %1
exit /b
:recurse
setlocal
set fileCnt=0
for /d %%D in ("%~1\*") do call :recurse "%%~fD"
for /f %%F in ('dir /b /a-d "%~1\*" 2^>nul ^| find /v /c ""') do (
set /a fileCnt+=%%F
)
pushd "%~f1" 2>nul
set "$date="
for /f "delims=" %%x in ('dir /b/o-d') do (set $date=%%~tx
set $date=!$date:~6,4!)
popd
echo %~f1 has %fileCnt% files and the oldest file is from year !$date!
(
endlocal
set /a fileCnt+=%fileCnt%
)
exit /b
You can use this one with 2 FOR
loop which is more compact and more easy :
@echo off
setlocal enableDelayedExpansion
for /f "delims=" %%a in ('dir /b/ad/s "%1"') do (
pushd "%%a"
set $c=0
for /f %%x in ('dir /b/o-d/a-d') do (
set "$date=%%~tx"
set "$date=!$date:~6,4!"
set /a $c+=1)
popd
if !$c!==0 set $date=[Null]
echo %%a has !$c! files and the oldest file is from year !$date!
)
Upvotes: 0
Reputation: 79983
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
PUSHD "%sourcedir%"
setlocal DISABLEDELAYEDEXPANSION
SET /a grand=0
if "%~1"=="" (call :recurse ".") else call :recurse %1
ECHO Total=%grand%
POPD
GOTO :eof
:recurse
setlocal
for /d %%D in ("%~1\*") do call :recurse "%%~fD"
set /a fileCnt=0
SET "oldest="
for /f "delims=" %%F in ('dir /b /a-d /o-d "%~1\*" 2^>nul') do (
set /a fileCnt+=1
IF NOT DEFINED oldest FOR %%O IN ("%~1\%%~nxF") DO SET "oldest=%%~tO %~1\%%~nxF"
)
echo %~f1 has %fileCnt% files and the oldest file is from year %oldest:~6,4% %oldest%
(
ENDLOCAL
SET /a grand=%grand%+%fileCnt%
)
exit /b
GOTO :EOF
Slightly reformatted to suit my testing on test directory u:\sourcedir.
I set oldest
to both date and filename. Selecting the required data is a matter of appropriate substringing, and it would need to be gated on #files <> 0.
Intriguingly, SET /a grand=%grand%+%fileCnt%
worked whereas SET /a grand+=%fileCnt%
failed...
Upvotes: 0