Take the 2-minute tour ×

Apologies for the very long title, i was wondering if some one could help me out with this.

What I'm trying to do is read a file which contains, say, 10 different directory paths, get the latest file in that directory and read the last line from that file.

@echo off
setlocal enableextensions enabledelayedexpansion
echo Host: %host%
for /f "tokens=* delims=" %%I in (C:\temp\servers.txt) do (
    SET /A vidx=!vidx! + 1
    set var!vidx!=%%I
    echo Path-to-File: %%I
    for /f "tokens=* delims=" %%X in ('dir "%%I" /OD /B')  do (
    set newest=%%X
    echo %newest%

Here is the output:

Host: Windows7
Path-to-File: \\Windows7\C$\direct\log\direct
ECHO is off.
Path-to-File: \\Windows7\C$\temp
ECHO is off.

Thanks in advance for the help.

share|improve this question
Where you have echo %newest% try changing it to echo !newest! and see whether that makes any difference. –  rojo Feb 7 '13 at 20:11
wow..that worked..thanks a ton rojo..if this was reddit, i would have given u reddit gold!! just curious what is the difference..sorry i'm completely new to batch scripting. –  user2051904 Feb 7 '13 at 20:53
In a cmd prompt window, type help set and space bar four or five times until you get to the "Delayed environment variable expansion" section. –  rojo Feb 7 '13 at 21:06
The HELP system describes the difference. Type HELP SET from the command prompt and start reading about half-way through with the paragraph that begins "Finally, support for delayed environment variable expansion has been added..." –  dbenham Feb 7 '13 at 21:08
add comment

1 Answer

Excuse me, I am somewhat confused by your description. The Batch file below was written in accordance with I understood about your requirement.

@echo off
setlocal EnableDelayedExpansion

rem Process the file with the paths:
for /F "delims=" %%I in (C:\temp\servers.txt) do (
   echo Path-to-File: %%I
   rem Get the newest file in this directory
   for /F "delims=" %%X in ('dir "%%I" /OD /B') do (
      set "newest=%%~X"
   echo Newest-File: !newest!
   rem Read the last line from this file
   for /F "usebackq delims=" %%L in ("!newest!") do (
      set "lastLine=%%L"
   echo Last-Line: !lastLine!

I hope it helps...


share|improve this answer
cheers guys..got this working. :) –  user2051904 Feb 7 '13 at 21:31
add comment

Your Answer


