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.
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: