grab file name based on timestamp

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
mlong12
Posts: 3
Joined: 21 Sep 2011 12:57

grab file name based on timestamp

#1 Post by mlong12 » 21 Sep 2011 13:13

Okay so ive been searching for days on this, and ive gotten close, but still cant get it.

What I need to do is take the file name "myfile.vsd" of the last modified file in the folder and set it to a variable so I can eventually print it to pdf. Now, I have everything good except the user still has to specify the name of the document to be printed.

So here is what I basically have so far:

for /f "tokens=* delims=: " %%g in ('dir %file% /-q /a:-d /t:w /od') do echo %%g

and that does nothing than what the dir command would do. So what I want to do is have %%g run through that folder and either a. pick out the filename of the last modified file and shove it in a variable or b. compare the date/time the .bat runs with the modified time of the file and kick out of the loop when the difference is minimum.

And this is going to be run multiple times daily, so the accuracy of the time has to be more precise than daily.

Any help would be awesome as this has been driving me nuts all day!

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: grab file name based on timestamp

#2 Post by dbenham » 21 Sep 2011 20:57

You were close :)

I don't understand your use of the /q option - it doesn't seem relevant based on the requirements as you explain them.

Code: Select all

for /f "delims=" %%g in ('dir %file% /b /a-d /tw /od') do @set latestFile=%%~fg

/b option because all you want is the file name.

When the FOR command is finished, the last file processed will be stored in the variable. Because the directory is sorted by last written date, the variable will contain the most recent file. The directory only displays to the minute, but I think it actually sorts more accurately than that. (I could be wrong)

Dave Benham

mlong12
Posts: 3
Joined: 21 Sep 2011 12:57

Re: grab file name based on timestamp

#3 Post by mlong12 » 22 Sep 2011 05:47

Thank you! That worked perfectly for what I needed! The reason I had /-q is because being about 2 days into really learning anything about batch files, I was trying to get rid of the "summary" information after the last file. (where it summarizes the number of files and drives.) so that i could just let the for loop iterate all the way to the bottom of the sorted list and set my variable to the last %%g.

Anyways, thank you so much! it works perfectly!

Post Reply