问题
I have a need to determine what the newest file is in each subdirectory under a root folder and output that list to a text file showing both the filename and creation date. As an example, if the root directory is D:\Data which contains a total of 4 subdirectories, and one of those 4 contain a subdirectory, my output file should contain a list of only files (not including created folders) something like this:
D:\Data\folder1\filename 02/12/14
D:\Data\folder2\filename 03/02/14
D:\Data\folder3\filename 03/15/14
D:\Data\folder4\folder01\filename 01/22/14
I have checked other posts, but none seem do this specifically...
回答1:
Two options
@echo off
setlocal enableextensions enabledelayedexpansion
set "rootFolder=c:\somewhere"
:: option 1
echo --------------------------------------------------------------------------------
for /d /r "%rootFolder%" %%a in (.) do (
set "first="
for /f "delims=" %%b in ('dir /o-d /a-d /b "%%~fa\*" 2^>nul') do if not defined first (
set "first=1"
for %%c in ("%%~fa\%%b") do echo %%~tc %%~fc
)
)
:: option 2
echo --------------------------------------------------------------------------------
set "tempFile=%temp%\%~nx0.%random%.tmp"
dir /a-d /b /s /o-d "%rootFolder%" 2>nul >"%tempFile%"
set "oldFolder="
for /f "usebackq delims=" %%a in ("%tempFile%") do if not "%%~dpa"=="!oldFolder!" (
echo %%~ta %%~fa
set "oldFolder=%%~dpa"
)
del /q "%tempFile%" >nul 2>nul
Option 1 will recurse over the folders structure and for each one, a dir
command is executed to retrieve the list of files in the folder in descending date order. The first in the list is the most rececent one.
Option 2 will use only one dir
command to retrieve the full list of files in descending date order and will save the retrieved information in a temporary file. Then the file is processed. Each time the name of the folder changes, output the first line that will be the most recent file in the folder.
Option 1 will start earlier to echo information, but as multiple commands are used, it will require more time to execute, but needs less memory as it will only retrieve the file list of one folder each time.
Option 2 uses less commands and will be faster, but uses a temporary file and requires more memory that Option 1 as the full file list will be loaded in memory.
Select depending of how deep is your folder structure, how much files you have, how much memory, .... just test.
来源:https://stackoverflow.com/questions/24143084/generate-a-list-of-the-newest-file-in-each-subdirectory-in-windows-batch