user3297825
user3297825

Reputation: 1

Finding the newest file in a directory

I am a complete novice in batch programming but have found some great scripts in here that I tried modifying. I need the info on the last file modified in a directory. The script below gives me a file with info about file name and modification time. It searches through subdirectories too but seems to get stuck in a subdirectory instead of finding the newer file in the parent directory. I am not sure what could be wrong (as I only partly understand the code). Any suggestions from you smart guys in here?

Thanks in advance!

@echo off

setlocal

set srcDir=C:\Test

set lastmod=

pushd "%srcDir%"

for /f "tokens=*" %%a in ('dir *. * /b /od /s /a-d 2^>NUL') do set lastmod=%%a

if "%lastmod%"=="" echo Could not locate files.&goto :eof

for /d %%a in ("%lastmod%") do echo "%lastmod%", Modified date: %%~ta>"C:\Test\Details.txt"

Upvotes: 0

Views: 844

Answers (1)

MC ND
MC ND

Reputation: 70961

This uses robocopy so it will only work on windows Vista and later. For it to work on XP you will need to get a copy of robocopy from a later OS or from resource kit.

No copy operation will really be made, but it will allow to retrieve a recursive file list with an adequated file stamp that can be sorted to find latest file.

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "folder=%cd%"

    for /f "tokens=2,*" %%a in (
        'robocopy "%folder%" "%folder%" "*" /s /is /nocopy /nc /ns /ts /fp /np /ndl /njh /njs /xjd /r:0 /w:0 /l ^| sort /r '
    ) do ( set "latest=%%b" & goto :done )
    :done

    for %%f in ("%latest%") do echo(%%~tf %%~ff

Upvotes: 1

Related Questions