Home > Back-end >  How to get most recent file in a directory without using a FOR loop?
How to get most recent file in a directory without using a FOR loop?

Time:10-06

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.

CodePudding user response:

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%

CodePudding user response:

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:            
  • Related