Question

I am having problems with the following batch file. On first run it doesn't output the date properly in the file. On first run i get the following:

*Start of batch file ~4,2dt:~6,2dt:~2,2dt:~8,2dt:~10,2* 
*End of batch file ~4,2dt:~6,2dt:~2,2dt:~8,2dt:~10,2*

on next run it works properly:

*Start of batch file 10/18/13 06:46*
*End of batch file 10/18/13 06:46*

One thing to note is that the log file didn't exist on the first run so it could be related to that?!?!?

Here is my Batch File:

set logFile=C:\log.txt
echo %logFile%

REM Get the Start Date and Time and Parse it out
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a 
set start=%dt:~4,2%/%dt:~6,2%/%dt:~2,2% %dt:~8,2%:%dt:~10,2%

ECHO Start of batch file %start% >>%logFile%
REM Run some procedure

REM Get the End Date and Time and Parse it out
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a 
set end=%dt:~4,2%/%dt:~6,2%/%dt:~2,2% %dt:~8,2%:%dt:~10,2%

ECHO End of batch file %end% >>%logFile%

Any help/suggestions would be greatly appreciated.

Was it helpful?

Solution

The contents of your For statement are expanded before executing and therefore dt is empty at first.

Add "setlocal ENABLEDELAYEDEXPANSION" to the top of your batch file. Also replace % with ! for all your expansions of dt. So the set start and end strings become "!dt:~4,2!/!dt:~6,2!/!dt:~2,2! !dt:~8,2!:!dt:~10,2!"

See the "set" help by running "set /?"

See How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top