windows 在批处理脚本中生成带有时间戳的唯一文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1642677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:52:00  来源:igfitidea点击:

Generate unique file name with timestamp in batch script

windowsbatch-filetimestampfilenames

提问by Assaf Lavie

In my .bat file I want to generate a unique name for files/directories based on date-time.

在我的 .bat 文件中,我想根据日期时间为文件/目录生成一个唯一的名称。

e.g.

例如

Build-2009-10-29-10-59-00

The problem is that %TIME%won't do because it contains characters that are illegal in filename (e.g. :).

问题是这%TIME%行不通,因为它包含文件名中非法的字符(例如:)。

Is there something like trin batch files?

tr批处理文件中有类似的东西吗?

Any other ideas how to solve this (that don't require extra command line utilities aside from the batch interpreter)?

如何解决这个问题的任何其他想法(除了批处理解释器之外不需要额外的命令行实用程序)?

回答by Joey

EDIT: A better way of doing this is to take a date/time string that has a defined and unchanging format instead of using the locale-defined ones from %date%and %time%. You can use the following to get it:

编辑:这样做的更好方法是采用具有定义和不变格式的日期/时间字符串,而不是使用来自%date%和的区域设置定义的%time%。您可以使用以下方法来获取它:

for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined mydate set mydate=%%x

It yields something like 20120730203126.530000+120and you can use that to construct your file names.

它产生类似的东西20120730203126.530000+120,您可以使用它来构造您的文件名。



(Old answer below)

(下面的旧答案)

You can simply replace the offending character with an empty string:

您可以简单地用空字符串替换有问题的字符:

echo %time::=%

The syntax %var:str1=str2%takes the environment variable (or pseudo-variable in case of %TIME%and replaces str1by str2. If nothing follows after the equals sign then str1is simply deleted.

语法%var:str1=str2%采用环境变量(或在情况下为伪变量%TIME%并替换str1str2。如果等号后没有任何内容,str1则简单地删除。

In your specific case I think you'd want the following:

在您的具体情况下,我认为您需要以下内容:

rem cut off fractional seconds
set t=%time:~0,8%
rem replace colons with dashes
set t=%t::=-%
set FileName=Build-%date%-%t%

A more brute-force way in case you don't know whether colons are used (but the order of the time would be the same):

如果您不知道是否使用了冒号(但时间顺序是相同的),则采用更强力的方法:

set FileName=Build-%date%-%time:~0,2%-%time:~3,2%-%time:~6,2%

All preceding things, however, assume that you use standard ISO 8601 date format, i.?e. 2009-10-29. I'd assume this as simply normal, but some people use other formats so be careful. But since you didn't ask about the date I was assuming you didn't have a problem there.

但是,前面的所有内容都假定您使用标准 ISO 8601 日期格式,即 2009-10-29。我认为这很正常,但有些人使用其他格式,所以要小心。但是由于您没有询问日期,我假设您在那里没有问题。

回答by Evgeni Sergeev

Following up on @Joey's and @Kees' answers to make them instantly usable.

跟进@Joey 和@Kees 的回答,使它们立即可用。

On the command line:

在命令行上:

FOR /f %a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%a
SET DateTime=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%_%DTS:~8,2%-%DTS:~10,2%-%DTS:~12,2%
echo %DateTime%

In a BAT file:

在 BAT 文件中:

@echo off
REM See http://stackoverflow.com/q/1642677/1143274
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a
SET DateTime=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%_%DTS:~8,2%-%DTS:~10,2%-%DTS:~12,2%
echo %DateTime%

Example output:

示例输出:

2014-10-21_16-28-52

回答by Ben

I use this to create a unique file name for the execution of the batch file.

我用它来为批处理文件的执行创建一个唯一的文件名。

REM ****Set up Logging ****
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
set mytime=%mytime: =0%

set Logname="PCCU_%mydate%_%mytime%.log"
Echo.  >>%Logname% 2>>&1
Echo.=================== >>%Logname% 2>>&1

I had to add the line

我不得不添加行

set mytime=%mytime: =0%

because I had the same problem where a blank was being entered before 10 AM, now I get 09 instead of 9. I also reuse the %mydate% and %mytime% variable for other files that I create with this script so that they all have the same date time stamp.

因为我遇到了同样的问题,在上午 10 点之前输入了一个空白,现在我得到了 09 而不是 9。我还为我使用此脚本创建的其他文件重用了 %mydate% 和 %mytime% 变量,以便它们都有相同的日期时间戳。

回答by Kees

This routine, actually only one line, works on every system set to any date or time format.
Output of line 1 is in format 20140725095527.710000+120

这个例程实际上只有一行,适用于设置为任何日期或时间格式的每个系统。
第 1 行的输出格式为 20140725095527.710000+120

The actual date/time format you need is determined in line 2. You can format it however you want.
Just add the resulting DateTime variable to your filename ie. Filename_%DateTime%.log

您需要的实际日期/时间格式在第 2 行中确定。您可以根据需要对其进行格式化。
只需将生成的 DateTime 变量添加到您的文件名,即。文件名_%DateTime%.log

::=======================================================================
::== CREATE UNIQUE DateTime STRING IN FORMAT YYYYMMDD-HHMMSS
::=======================================================================
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a

SET DateTime=%DTS:~0,8%-%DTS:~8,6% | REM OUTPUT = 20140725-095527

回答by Ariful Huq

I made this universal, Will work on any environment where date format may be different.

我使这个通用,适用于日期格式可能不同的任何环境。

echo off
if not exist "C:\SWLOG\" mkdir C:\SWLOG
cd C:\SWLOG\
cmd /c "powershell get-date -format ^"{yyyyMMdd-HHmmss}^""> result.txt
REM echo %time% > result.txt
type result.txt > result1.txt
set /p filename=<result1.txt
echo %filename%
del C:\SWLOG\result.txt
del C:\SWLOG\result1.txt

回答by Stewart

To make the code in the previous example work, I needed to adjust slightly. I presume this is because my PC is using a UK date format. To get back "2014-04-19" in mydate I needed:

为了使上一个示例中的代码正常工作,我需要稍微调整一下。我认为这是因为我的 PC 使用的是英国日期格式。要在 mydate 中取回“2014-04-19”,我需要:

For /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)

Below I've pasted my total script, and included an example of how to use the filename

下面我粘贴了我的总脚本,并包含了一个如何使用文件名的示例

For /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%b-%%a)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
set mytime=%mytime: =0%

set Logname="c:\temp\LogFiles\MyLogFile_%mydate%_%mytime%.log"
Robocopy  \sourceserver\Music H:\MyBackups\Music /MIR /FFT /Z /XA:H /W:5 /np /fp /dcopy:T /unilog:%Logname% /tee 

Hope this helps!

希望这可以帮助!

回答by Colin Basnett

If you can guaranteethat the machine has a specific version of Python installed on it and accessible in the system's PATH, you can use this solution:

如果你能保证机器上安装了特定版本的 Python 并且可以在系统的 中访问PATH,你可以使用这个解决方案:

FOR /F "tokens=* USEBACKQ" %%F IN (`python -c "import datetime; print 
datetime.datetime.now().replace(microsecond=0).isoformat().replace(':', '-')"`) DO (
SET TIMESTAMP=%%F
)
ECHO %TIMESTAMP%

This will put the current local ISO-8601(ish) date representation into a %TIMESTAMP%variable and echo it out, like so:

这会将当前的本地ISO-8601(ish) 日期表示形式放入一个%TIMESTAMP%变量中并将其回显出来,如下所示:

2017-05-25T14:54:37

I've put replace(':', '-')after the isoformat()so that the resultant string can be used in a filename or directory, since :is a forbidden character in the Windows filesystem.

我已将其放在replace(':', '-')后面,isoformat()以便可以在文件名或目录中使用结果字符串,因为它:是 Windows 文件系统中的禁止字符。