1

I'm trying to write a batch file that returns the most recent file in a directory without using a for loop. I tried a lot but it's not working.

So is there a approach that we can get the most recent file without using for loop?

@echo off  
cd D:\Applications  
for /f "delims=" %%i in ('dir /b/a-d/od/t:c') do set RECENT="%%~nxi"  
echo ..... starting jar........  
start java -jar %RECENT%  
echo ....jar started.....  
exit 0

The execution gets stuck at start java and it does not go to next line or exit 0.

Mofi
  • 46,139
  • 17
  • 80
  • 143
Abhinandan RK
  • 47
  • 1
  • 10
  • so if you change `echo ..... starting jar` to `echo ..... starting jar: %RECENT%`, does it show the (correct) file? – Stephan Oct 05 '21 at 13:06
  • yes it does shows the correct file if i use ... starting jar : %RECENT% – Abhinandan RK Oct 05 '21 at 15:18
  • This answer your _question_, but don't solve your _problem_ (as @Stephan already said): `dir /O:-D /B > file.txt & set /P "RECENT=" < file.txt` – Aacini Oct 06 '21 at 16:11

2 Answers2

2

I'm not sure why you don't want to use the most powerful command in cmd, but for the sake of answering your question:

dir /o-d /b "C:\my folder\*" >tmp
<tmp set /p "latest="
del tmp
echo the latest file is %latest%
Stephan
  • 53,940
  • 10
  • 58
  • 91
2

There can be used the following code using command FOR:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
cd /D "D:\Applications" 2>nul || (echo ERROR: Directory D:\Applications does not exist.& goto EndBatch)
for /F "eol=| delims=" %%i in ('dir /A-D /B /O-D /TC 2^>nul') do set "RECENT=%%i" & goto StartJava
echo WARNING: Could not find any file in directory: "%CD%"& goto EndBatch
:StartJava
if exist %SystemRoot%\System32\where.exe %SystemRoot%\System32\where.exe java.exe >nul 2>nul
if errorlevel 1 echo ERROR: Could not find java.exe. Check environment variable PATH.& goto EndBatch
echo ..... Starting jar .....
start "Running %RECENT%" java.exe -jar "%RECENT%"
if not errorlevel 1 echo ..... jar started .....
:EndBatch
if errorlevel 1 echo(& pause
endlocal

There is some error handling also added to the code.

Please note that the creation date is the date of a file on being created in the current directory. So if a file is copied from directory X to directory Y, its last modification date is not modified, but the file has a new creation date in directory Y which is newer than its last modification date.

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • cd /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • set /?
  • setlocal /?
  • start /?
  • where /?

See also:

Mofi
  • 46,139
  • 17
  • 80
  • 143