your programing

일괄 작업에서 파일 이름을 타임 스탬프로 만들기

lovepro 2020. 10. 4. 12:57
반응형

일괄 작업에서 파일 이름을 타임 스탬프로 만들기


매일 실행되는 배치 작업이 있으며 파일을 픽업 폴더에 복사합니다. 또한 해당 파일의 사본을 가져 와서 파일 이름이있는 보관 폴더에 드롭하고 싶습니다.

 yyyy-MM-dd.log

Windows 배치 작업에서이 작업을 수행하는 가장 쉬운 방법은 무엇입니까?

기본적으로이 Unix 명령에 해당하는 것을 찾고 있습니다.

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

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

그러나 로케일에 따라 다릅니다. %DATE%이 지역화 되었는지 확실하지 않거나 Windows의 짧은 날짜에 지정된 형식에 따라 다릅니다.

여기에서 현재 날짜 추출하는 로케일 독립적 인 방법 이 대답은 하지만에 따라 달라집니다 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

이것은 나를 위해 일했으며 파일 이름에 안전한 솔루션이었습니다 (MM-dd-YYYY 형식을 생성하지만).

C:\ set SAVESTAMP=%DATE:/=-%@%TIME::=-%
C:\ set SAVESTAMP=%SAVESTAMP: =%
C:\ set SAVESTAMP=%SAVESTAMP:,=.%.jpg
C:\ echo %SAVESTAMP%
11-04-2012@20-52-42.79.jpg

첫 번째 명령은 날짜와을 대체 소요 /로를 -, 시간과을 대체한다 :과를 -, 및 시간 형식 @ DATE로 콤바인을. 두 번째 set문은 공백, 세 번째 제거 set을 대체 ,와를 .하고 추가 .jpg확장을.

위의 코드는 추가 처리를 위해 보안 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

들어 프랑스어 로케일 (프랑스) 만 주의 때문에 /날짜에 나타납니다 :

echo %DATE%
08/09/2013

로그 파일 문제에 대한 내 제안은 프랑스어 로케일 전용입니다 .

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%

다음은 로케일 독립적 솔루션입니다 (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%

모든 .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%

예제에서 볼 수 있듯이 날짜 / 시간 값을 업데이트해야 할 때마다 SetDateTimeComponents.cmd를 호출 할 수 있습니다. 자체 SetDateTimeComponents.cmd 파일에 시간 구문 분석 스크립트를 숨기는 것은 추악한 세부 정보를 숨기고, 더 중요한 것은 오타를 피하는 좋은 방법입니다.


이렇게하면 출력이 2 자리 값인지 확인할 수 있습니다. 원하는대로 출력을 재 배열하고 진단 섹션의 주석 처리를 제거하여 테스트 할 수 있습니다. 즐겨!

(다른 포럼에서 많이 빌 렸습니다 ...)

:: ------------------ 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%

나는 이것을 자주 사용하고 모든 것을 단일 복사 명령에 넣습니다. 다음은 example.txt를 example_YYYYMMDD_HHMMSS.txt로 복사하며 물론 원하는 형식에 맞게 수정할 수 있습니다. 따옴표는 filespec에 공백이있는 경우에만 필요합니다. 정확히 동일한 날짜 / 타임 스탬프를 다시 사용하려면 변수에 저장해야합니다.

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

찢어의 생각 때문에 %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

NET 스타일 및 UNIX 스타일 모두에 대한 형식 옵션이있는에 대한 참조 get-date여기 입니다.


현재 날짜를 파일 이름으로 파일 만들기 (예 : 2008-11-08.dat)

echo hello > %date%.dat    

현재 날짜는 있지만 "-"는 제외 (예 : 20081108.dat)

echo hello > %date:-=%.dat   

도움이 될 수 있습니다.

echo off
@prompt set date=$d$_ set time=$t$h$h$h
echo some log >> %date% %time%.log
exit

또는

echo off
set v=%date%.log
echo some log >> %v%

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:

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


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

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:

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

1) You can download GNU coreutils which comes with GNU date

2) you can use VBScript, which makes date manipulation easier in Windows:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
Set objFolder = objFS.GetFolder(strFolder)
current = Now
mth = Month(current)
d = Day(current)
yr = Year(current)
If Len(mth) <2 Then
    mth="0"&mth
End If
If Len(d) < 2 Then
    d = "0"&d
End If
timestamp=yr & "-" & mth &"-"& d
For Each strFile In objFolder.Files
    strFileName = strFile.Name
    If InStr(strFileName,"file_name_here") > 0 Then
        BaseName = objFS.GetBaseName(strFileName)
        Extension = objFS.GetExtensionName(strFileName)
        NewName = BaseName & "-" & timestamp & "." & Extension
        strFile.Name = NewName
    End If
Next

Run the script as:

c:\test> cscript /nologo myscript.vbs

I know this thread is old but I just want to add this here because it helped me alot trying to figure this all out and its clean. The nice thing about this is you could put it in a loop for a batch file that's always running. Server up-time log or something. That's what I use it for anyways. I hope this helps someone someday.

@setlocal enableextensions enabledelayedexpansion
@echo off

call :timestamp freshtime freshdate
echo %freshdate% - %freshtime% - Some data >> "%freshdate - Somelog.log"

:timestamp
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
set FreshTime=%hour%:%min%:%secs%

set year=%date:~-4%
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~7,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set FreshDate=%month%.%day%.%year%

This works well with (my) German locale, should be possible to adjust it to your needs...

forfiles /p *PATH* /m *filepattern* /c "cmd /c ren @file 
%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_@file"

For big zip files for deployment, I use quarter hours. No one else on this page had mentioned it before, so I'll put my small script here:

set /a "quarter_hours=%time:~0,2%*4 + %time:~3,2% / 15"
set "zip_file=release_%DATE:~-4%.%DATE:~4,2%.%DATE:~7,2%.%quarter_hours%.zip"

It doesn't zero pad quarter hours from midnight to 5am yet, but it still makes it so you can have a stamped release multiple times a day with few collisions.

Hope that helps.

참고URL : https://stackoverflow.com/questions/1064557/creating-a-file-name-as-a-timestamp-in-a-batch-job

반응형