Fiend
Fiend

Reputation: 11

Batch script to show in txt file latest file available in a directory, by date

I have this simple batch script:

@echo off
dir /o-d "K:\DIR\DIR\*.exe" > "D:\Logs\Files.txt"

which displays all the files in a txt, by date.

My question is: how can I get this to show me only the last file by date and not all files in that specific directory?

Thanks in advance.

Upvotes: 1

Views: 1263

Answers (4)

Alessandro Da Rugna
Alessandro Da Rugna

Reputation: 4695

to get only the file name of the latest file

@echo off
for /f "tokens=*" %%x in ('dir /b /o-d "K:\DIR\DIR\*.exe"') do (
    echo %%x
    exit /b 0
)

Upvotes: 0

wmz
wmz

Reputation: 3685

@echo off
setlocal 
for /f "delims=" %%F in ('dir /b /o-d') do (
  set file=%%~nxF %%~tF
  goto display
)
:display
echo %file%

Notes:

  • To understand for and 'decrypt' %%~nxF %%~tF, read for help (help for from command line)
  • goto is there just to break the loop after first (latest) file/dir.
  • To redirect to file, either redirect the batch itself (batch.bat >myFile) or last echo (echo %file% > myFile)
  • Dir matches subdirectories as well as files by default. Use dir /a-d to match files only.

Upvotes: 1

Eitan T
Eitan T

Reputation: 32920

Retrieving the last line

If you're only interested in the last file, you can do this:

@echo off
for /f "tokens=*" %%a in ('dir /o-d "K:\DIR\DIR*.exe" ^| findstr /C:"/"') do set last=%%a
echo %last%

This displays only the last filename from the output of the dir command. If you want to redirect it to a file, replace echo %last% with:

echo %last% > "D:\Logs\Files.txt"

Retrieving the first line

If you're interested in the first file, you need to slightly alter the code to this:

for /f "tokens=*" %%a in ('dir /o-d "K:\DIR\DIR*.exe" ^| findstr /C:"/"') do set first=%%a && goto Done
:Done
echo %first%

Again, if you're interested in redirecting it to a file, replace echo %first% with:

echo %first% > "D:\Logs\Files.txt"

Upvotes: 2

Riskhan
Riskhan

Reputation: 4470

I think it is not possible using shell/batch commands.

you may write another program to pick first line of Files.txt file

Upvotes: 0

Related Questions