Windows批处理文件重定向输出到具有日期/时间的日志文件 [英] Windows batch file redirect output to logfile with date/time

查看:1332
本文介绍了Windows批处理文件重定向输出到具有日期/时间的日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行一个批处理文件,它运行一个可执行文件,并将其输出重定向到一个日志文件。日志文件必须具有日期和时间作为文件名。这是我使用的命令:

I am trying to run a batch file which runs an executable and redirects its output to a log file. The log file must have the date and time as the file name. This is the command I am using:

"%PROGRAMFILES%\PostgreSQL\9.4\bin\vacuumdb.exe" --username postgres --verbose --analyze --all > E:\Logs\VacuumDB\%date:~10,4%_%date:~4,2%_%date:~7,2%_%time:~0,2%_%time:~3,2%_%time:~6,2%.log 2>&1

命令工作时直接粘贴在cmd。日志文件按预期创建为2015_06_25__11_20_46.log。但是,它粘贴在批处理文件中时不工作,然后在cmd中运行。 Cmd将命令解释如下:

This command works when pasted directly in cmd. The log file is created as expected as '2015_06_25__11_20_46.log'. However, it does not work when pasted in a batch file, and then run in cmd. Cmd interprets the command as follow:

"C:\Program Files\PostgreSQL\9.4\bin\vacuumdb.exe" --username postgres --verbose --analyze --all  8_21_42.log  1>E:\Logs\VacuumDB\2015_06_26_ 2>&1

请注意文件名是如何被截断的,并且现在将时间附加到命令参数,而不是在文件名中。所以显然命令失败。

Notice how the file name is truncated and the time is now appended to the command arguments instead of being in the file name. So obviously the command fails.

这肯定是非常简单,但我没有找到任何办法来解决这个问题。非常感谢任何帮助。

This is surely something very simple but I have not found any way to fix this. Any help is greatly appreciated.

谢谢!

推荐答案

问题是,时间戳可能包含一个空格(在10点之前)
您可以将其替换为零< a>,但我建议使用与地区设置无关的解决方案

Your problem is, that the timestring may contain a space (before 10 o'clock) You can replace it with a zero, but I recommend a solution independent of locale settings:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

它会给你(独立于区域设置!):

It will give you (independent of locale settings!):

  20130802203023.304000+120 
( YYYYMMDDhhmmss.<fraction>+/-<timedifference to UTC>  )

从这里,它很容易格式化到您的需要。例如:

from here, it is easy to format it to your needs. For example:

set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023

这篇关于Windows批处理文件重定向输出到具有日期/时间的日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆