Windowsbatch file中的date分析

我遇到了以下batch file的问题。 首次运行时,它不会在文件中正确输出date。 在第一次运行我得到以下内容:

*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* 

在下一次运行它正常工作:

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

有一点需要注意的是,第一次运行时日志文件不存在,所以它可能与此相关?!?!?

这是我的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% 

任何帮助/build议将不胜感激。

你的For语句的内容在执行之前被扩展,所以dt首先是空的。

将“setlocal ENABLEDELAYEDEXPANSION”添加到批处理文件的顶部。 也用%替换%! 为你所有的扩展dt。 因此,设定的开始和结束字符串变成“!dt:〜4,2!/!dt:〜6,2!/!dt:〜2,2!!dt:〜8,2!:!dt:〜10, 2!”

通过运行“set /?”来查看“set”帮助

请参阅SETLOCAL和ENABLEDELAYEDEXPANSION如何工作?