1

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.

Bucket
  • 7,415
  • 9
  • 35
  • 45
James Smith
  • 1,072
  • 1
  • 11
  • 14

1 Answers1

2

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?

Community
  • 1
  • 1
Okkenator
  • 1,654
  • 1
  • 15
  • 27