windows 在批处理作业中创建文件名作为时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1064557/
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:32:57  来源:igfitidea点击:

Creating a file name as a timestamp in a batch job

windowsbatch-filecmdtimestamp

提问by Eoin Campbell

We have a batch job that runs every day and copies a file to a pickup folder. I want to also take a copy of that file and drop it into an archive folder with the filename

我们有一个每天运行的批处理作业,并将一个文件复制到一个拾取文件夹。我还想复制该文件并将其放入具有文件名的存档文件夹中

 yyyy-MM-dd.log

What's the easiest way to do this in a Windows batch job?

在 Windows 批处理作业中执行此操作的最简单方法是什么?

I'm basically looking for an equivalent of this Unix command:

我基本上是在寻找与此 Unix 命令等效的命令:

cp source.log `date +%F`.log

回答by opello

CP source.log %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.log

But it's locale dependent. I'm not sure if %DATE%is localized, or depends on the format specified for the short date in Windows.

但它依赖于语言环境。我不确定是否%DATE%已本地化,或者取决于为 Windows 中的短日期指定的格式。

Here is a locale-independent way to extract the current date from this answer, but it depends on WMICand FOR /F:

这是从该答案中提取当前日期的一种与语言环境无关的方法,但它取决于WMICFOR /F

FOR /F %%A IN ('WMIC OS GET LocalDateTime ^| FINDSTR \.') DO @SET B=%%A
CP source.log %B:~0,4%-%B:~4,2%-%B:~6,2%.log

回答by Daniel Sokolowski

This worked for me and was a filename-safe solution (though it generates a MM-dd-YYYY format):

这对我有用并且是文件名安全的解决方案(尽管它生成了 MM-dd-YYYY 格式):

C:\ set SAVESTAMP=%DATE:/=-%@%TIME::=-%
C:\ set SAVESTAMP=%SAVESTAMP: =%
C:\ set SAVESTAMP=%SAVESTAMP:,=.%.jpg
C:\ echo %SAVESTAMP%
[email protected]

The first command takes a DATE and replaces /with -, takes the TIME and replaces :with -, and combines them into DATE@TIME format. The second setstatement removes any spaces, and the third setreplaces ,with .and appends the .jpgextension.

第一个命令采用 DATE 并替换/-,采用 TIME 并替换:-,并将它们组合成 DATE@TIME 格式。第二个set语句删除任何空格,而第三set内容替换,.和追加.jpg延长。

The above code is used in a little script that pulls images from a security IP Camera for further processing:

上面的代码在一个小脚本中使用,该脚本从安全 IP 摄像机中提取图像以进行进一步处理:

:while
set SAVESTAMP=%DATE:/=-%@%TIME::=-%
set SAVESTAMP=%SAVESTAMP: =%
set SAVESTAMP=%SAVESTAMP:,=.%.jpg
wget-1.10.2.exe --tries=0 -O %SAVESTAMP% http://admin:<password>@<ip address>:<port>/snapshot.cgi
timeout 1
GOTO while

回答by Aubin

For French Locale (France) ONLY, be careful because /appears in the date :

对于French Locale (France) ONLY,要小心,因为/出现在日期中:

echo %DATE%
08/09/2013

For our problem of log file, here is my proposal for French Locale ONLY:

对于我们的日志文件问题,这是我对法语语言环境的建议:

SETLOCAL
set LOGFILE_DATE=%DATE:~6,4%.%DATE:~3,2%.%DATE:~0,2%
set LOGFILE_TIME=%TIME:~0,2%.%TIME:~3,2%
set LOGFILE=log-%LOGFILE_DATE%-%LOGFILE_TIME%.txt
rem log-2014.05.19-22.18.txt
command > %LOGFILE%

回答by totorocat

Here is a locale independent solution (copy to a file named SetDateTimeComponents.cmd):

这是一个独立于语言环境的解决方案(复制到名为 SetDateTimeComponents.cmd 的文件):

@echo off
REM This script taken from the following URL:
REM http://www.winnetmag.com/windowsscripting/article/articleid/9177/windowsscripting_9177.html

REM Create the date and time elements.
for /f "tokens=1-7 delims=:/-, " %%i in ('echo exit^|cmd /q /k"prompt $d $t"') do (
   for /f "tokens=2-4 delims=/-,() skip=1" %%a in ('echo.^|date') do (
      set dow=%%i
      set %%a=%%j
      set %%b=%%k
      set %%c=%%l
      set hh=%%m
      set min=%%n
      set ss=%%o
   )
)

REM Let's see the result.
echo %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss%

I put all my .cmd scripts into the same folder (%SCRIPTROOT%); any script that needs date/time values will call SetDateTimeComponents.cmd as in the following example:

我把我所有的 .cmd 脚本放到同一个文件夹中 (%SCRIPTROOT%); 任何需要日期/时间值的脚本都将调用 SetDateTimeComponents.cmd,如下例所示:

setlocal

@echo Initializing...
set SCRIPTROOT=%~dp0
set ERRLOG=C:\Oopsies.err

:: Log start time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : Start === >> %ERRLOG%

:: Perform some long running action and log errors to ERRLOG.

:: Log end time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : End === >> %ERRLOG%

As the example shows, you can call SetDateTimeComponents.cmd whenever you need to update the date/time values. Hiding the time parsing script in it's own SetDateTimeComponents.cmd file is a nice way to hide the ugly details, and, more importantly, avoid typos.

如示例所示,您可以在需要更新日期/时间值时调用 SetDateTimeComponents.cmd。将时间解析脚本隐藏在它自己的 SetDateTimeComponents.cmd 文件中是隐藏丑陋细节的好方法,更重要的是,可以避免拼写错误。

回答by tboz203

Because the idea of tearing %DATE%and %TIME%apart and mashing them back together seems fragile at best, here's an alternative that uses a powershell oneliner:

因为将它们撕裂%DATE%%TIME%分开并将它们重新组合在一起的想法充其量看起来很脆弱,所以这里有一个使用 powershell oneliner 的替代方案:

for /f %i in ('powershell -c "get-date -format yyyy-MM-dd--HH-mm-ss"') do @set DATETIME=%i
set LOGFILE=my-script-%DATETIME%.txt

Reference for get-dateis here, with format options for both .NET-style and UNIX-style.

参考get-datehere,包含 .NET 风格和 UNIX 风格的格式选项。

回答by BeConcise

I frequently use this, and put everything into a single copy command. The following copies example.txt as example_YYYYMMDD_HHMMSS.txt and of course you can modify it to suit your preferred format. The quotes are only necessary if there are any spaces in the filespec. If you want to reuse the exact same date/timestamp, you'd need to store it in a variable.

我经常使用它,并将所有内容放入一个复制命令中。以下将 example.txt 复制为 example_YYYYMMDD_HHMMSS.txt,当然您可以修改它以适合您的首选格式。仅当文件规范中有任何空格时才需要引号。如果要重用完全相同的日期/时间戳,则需要将其存储在变量中。

copy "{path}\example.txt" "{path}\_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"

回答by Rick Rubino

This will ensure that the output is a 2-digit value...you can rearrange the output to your liking and test by un-commenting the diagnostics section. Enjoy!

这将确保输出是一个 2 位数的值...您可以根据自己的喜好重新排列输出并通过取消注释诊断部分来测试。享受!

(I borrowed a lot of this from other forums...)

(我从其他论坛借用了很多……)

:: ------------------ Date and Time Modifier ------------------------

@echo off
setlocal

:: THIS CODE WILL DISPLAY A 2-DIGIT TIMESTAMP FOR USE IN APPENDING FILENAMES

:: CREATE VARIABLE %TIMESTAMP%

for /f "tokens=1-8 delims=.:/-, " %%i in ('echo exit^|cmd /q /k"prompt $D $T"') do (
   for /f "tokens=2-4 skip=1 delims=/-,()" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set sec=%%o
set hsec=%%p
)
)

:: ensure that hour is always 2 digits

if %hh%==0 set hh=00
if %hh%==1 set hh=01
if %hh%==2 set hh=02
if %hh%==3 set hh=03
if %hh%==4 set hh=04
if %hh%==5 set hh=05
if %hh%==6 set hh=06
if %hh%==7 set hh=07
if %hh%==8 set hh=08
if %hh%==9 set hh=09


:: --------- TIME STAMP DIAGNOSTICS -------------------------

:: Un-comment these lines to test output

:: echo dayOfWeek = %dow%
:: echo year = %yy%
:: echo month = %mm%
:: echo day = %dd%
:: echo hour = %hh%
:: echo minute = %min%
:: echo second = %sec%
:: echo hundredthsSecond = %hsec%
:: echo.
:: echo Hello! 
:: echo Today is %dow%, %mm%/%dd%. 
:: echo.
:: echo. 
:: echo.
:: echo.
:: pause

:: --------- END TIME STAMP DIAGNOSTICS ----------------------

:: assign timeStamp:
:: Add the date and time parameters as necessary - " yy-mm-dd-dow-min-sec-hsec "

endlocal & set timeStamp=%yy%%mm%%dd%_%hh%-%min%-%sec%
echo %timeStamp%

回答by Adam Silenko

You can simply detect the current local format and can get the date in your format, for example:

您可以简单地检测当前的本地格式,并可以获取格式中的日期,例如:

::for 30.10.2016 dd.MM.yyyy
if %date:~2,1%==. set d=%date:~-4%%date:~3,2%%date:~,2%
::for 10/30/2016 MM/dd/yyyy
if %date:~2,1%==/ set d=%date:~-4%%date:~,2%%date:~3,2%
::for 2016-10-30 yyyy-MM-dd
if %date:~4,1%==- set d=%date:~,4%%date:~5,2%%date:~-2%
::variable %d% have now value: 2016103 (yyyyMMdd)
set t=%time::=%
set t=%t:,=%
::variable %t% have now time without delimiters
cp source.log %d%_%t%.log

回答by Dean

I know this is an old post, but there is a FAR simpler answer (though maybe it only works in newer versions of windows). Just use the /t parameter for the DATE and TIME dos commands to only show the date or time and not prompt you to set it, like this:

我知道这是一篇旧帖子,但有一个更简单的答案(尽管它可能只适用于较新版本的 Windows)。只需使用 DATE 和 TIME dos 命令的 /t 参数来仅显示日期或时间,而不提示您进行设置,如下所示:

@echo off
echo Starting test batch file > testlog.txt
date /t >> testlog.txt
time /t >> testlog.txt

回答by Harry Pehkonen

I put together a little C program to print out the current timestamp (locale-safe, no bad characters...). Then, I use the FOR command to save the result in an environment variable:

我整理了一个小 C 程序来打印当前时间戳(语言环境安全,没有坏字符......)。然后,我使用 FOR 命令将结果保存在环境变量中:

:: Get the timestamp
for /f %%x in ('@timestamp') do set TIMESTAMP=%%x

:: Use it to generate a filename
for /r %%x in (.\processed\*) do move "%%~x" ".\archived\%%~nx-%TIMESTAMP%%%~xx"

Here's a link:

这是一个链接:

https://github.com/HarryPehkonen/dos-timestamp

https://github.com/HarryPehkonen/dos-timestamp