记录命令的开始和结束时间并将其存储在CSV文件中

时间:2016-09-19 16:18:47

标签: windows datetime batch-file cmd output

我有一个批处理文件,我想知道运行多长时间然后输出日志文件结果为.csv格式的文件。期望的输出看起来像这样:

    Batch,Date,StartTime,EndTime
    AM,Sun 09/18/2016,07:00:00,07:53:42
    PM,Sun 09/18/2016,19:00:00,19:51:54
    AM,Mon 09/19/2016,07:01:22,07:56:54

“批处理”列只是脚本是在早上还是晚上运行。结果为“AM”或“PM”。我不知道如何做有条件的“如果”。但我在想这样的事情:

    set startdate = %date%
    set starttime = %time%

    Don't know how to do if/then/else so in words:
    if starttime is less than 12:00:00, then set batch="AM". Else set batch ="PM"

然后在我的文件末尾我放了:

    echo %batch%,%startdate%,%starttime%,%time% >> C:\backup_time.csv

1 个答案:

答案 0 :(得分:0)

首先,您的代码中存在下一个错误:

rem          ↓ ↓        harmful spaces
set startdate = %date%
set starttime = %time%
rem          ↑ ↑        harmful spaces

下一个代码段应按预期工作:

set "startdate=%date%"
set "starttime=%time%"
set "_aux=%starttime:~0,2%"          extract hours from time
set "_aux=%_aux: =0%"                change possible leading space to zero if necessary
    rem treat properly values 08 and 09 using modulo operator in next `SET /A` command
set /A "_aux=1%_aux% %% 100"
if %_aux% LSS 12 (set "batch=AM") else set "batch=PM"
>>C:\backup_time.csv echo %batch%,%startdate%,%starttime%,%time%

资源(必读,不完整):