Trick is using delayedExpansion and !time! instead of %time%. Practical example that lists files in current folder, one per second showing timestamp:
@echo off
setlocal enableextensions enabledelayedexpansion & REM read vars at exec with !varNm!
rem List of files sorted by name
for /f "usebackq delims=" %%x in (`dir "*.*" /b /on /a-d`) do (
rem Replace trailing space before 10AM hours
set dateTime=!date!/!time: =0!
rem Delims ., will separate seconds from its hundreds
for /f "tokens=1,2,3,4,5,6,7 usebackq delims=:/-,. " %%a in ('!dateTime!') do (
rem Local date format DD/MM/YYYY, change next line for other cases
rem Show date-time filename
echo %%c%%b%%a-%%d%%e%%f %%x
)
rem wait 1 second aprox
ping 10.0.0.201 -n 1 -w 1000 >nul
)
Better approach local independent using Stephan's answer:
Batch command date and time in file name
@echo off
setlocal enableextensions enabledelayedexpansion
for /f "usebackq delims=" %%x in (`dir "*.*" /b /on /a-d`) do (
for /f "tokens=2 delims==.," %%I in ('wmic os get localdatetime /format:list') do set dateTime=%%I
echo !datetime:~2,6!-!datetime:~8,6! %%x
ping 10.0.0.201 -n 1 -w 1000 >nul
)
%%a
,...%%e
are yourfor
-variables. Don't change them. Use!time!
instead of%time%
(and!date!
instead of%date%
- just in case, your script runs about midnight ;)). But you will find a better way for Date-Time-string here – Rhizogenic%date%
for getting the date. It's unreliable because it depends on the current locale and datetime setting. See How to get Windows batch date stamp that is locale independent? – Cosmetic