태그 보관물: batch

batch

배치 파일로 날짜를 예측 가능한 형식으로 얻는 방법은 무엇입니까? 문자열을 변수로 추출합니다. set Day=%Date:~3,2% set Mth=%Date:~0,2% set

배치 파일에서 date 명령에서 월, 일, 년을 추출해야합니다. 따라서 다음을 사용하여 기본적으로 Date 명령을 구문 분석하여 하위 문자열을 변수로 추출합니다.

set Day=%Date:~3,2%
set Mth=%Date:~0,2%
set Yr=%Date:~6,4%

이것은 모두 훌륭하지만이 배치 파일을 다른 지역 / 국가 설정이있는 컴퓨터에 배포하면 월, 일 및 연도가 다른 위치에 있기 때문에 실패합니다.

날짜 형식에 관계없이 월, 일 및 연도를 추출하려면 어떻게해야합니까?



답변

출처 : http://ss64.com/nt/syntax-getdate.html

방법 2 (단일 cmd)

GetDate.cmd

@Echo off
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _yyyy=%%L
      Set _mm=00%%J
      Set _dd=00%%G
      Set _hour=00%%H
      SET _minute=00%%I
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%
      Set _hour=%_hour:~-2%
      Set _minute=%_minute:~-2%

:: Display the date/time in ISO 8601 format:
Set _isodate=%_yyyy%-%_mm%-%_dd% %_hour%:%_minute%
Echo %_isodate%
pause

여기에 이미지 설명을 입력하십시오


방법 1 (cmd + vb)

GetDate.cmd

@Echo off
For /f %%G in ('cscript /nologo getdate.vbs') do set _dtm=%%G
Set _yyyy=%_dtm:~0,4%
Set _mm=%_dtm:~4,2%
Set _dd=%_dtm:~6,2%
Set _hh=%_dtm:~8,2%
Set _nn=%_dtm:~10,2%
Echo %_yyyy%-%_mm%-%_dd%T%_hh%:%_nn%

getdate.vbs

Dim dt
dt=now
'output format: yyyymmddHHnn
wscript.echo ((year(dt)*100 + month(dt))*100 + day(dt))*10000 + hour(dt)*100 + minute(dt)


답변

Windows XP 이상

getDate.cmd

@echo off
for /f "tokens=2 delims==" %%G in ('wmic os get localdatetime /value') do set datetime=%%G

set year=%datetime:~0,4%
set month=%datetime:~4,2%
set day=%datetime:~6,2%

echo %year%/%month%/%day%

산출

여기에 이미지 설명을 입력하십시오


답변

정확히 요청한 것은 아니지만 date배치 파일 내부의 명령에서 Linux 응용 프로그램 의 Windows 포트를 사용한 다음 결과를 변수에 할당합니다.

배치 명령 만 사용하여 날짜를 안정적으로 얻는 방법을 아직 찾지 못했습니다.


답변

이 배치 파일을 YYYY-MM-DD 형식으로 사용하십시오. 최신 모든 Windows 버전에 있어야하는 창 계측 도구를 사용하여 지역 설정과 무관 한 날짜 시간 문자열을 얻습니다.

배치 파일에 경로 (예 : c : \ windows \ rdate.bat)에 저장 한 다음 CALL RDATE.BAT를 사용하여 변수를 설정하십시오. 또는 코드를 배치 파일에 복사하십시오.

이 날짜 형식은 파일 이름 및 로깅에 적합합니다. 올바르게 정렬됩니다. logtime 변수는 두 번째 정확도로 배치 파일 활동을 로깅하는 데 적합한 날짜 + 시간 변수를 YYYY-MM-DD-HHMMSS로 추가합니다.

원하는대로 날짜 및 시간 형식을 조정하십시오. REM 프로덕션에서 화면이 에코됩니다. 각 텍스트 선택에서 두 숫자는 0부터 시작하는 문자 색인이며 복사 할 문자 수입니다. 예를 들어 % datetime : ~ 0,4 %는 위치 0에서 시작하는 4 문자 하위 문자열을 사용합니다.

echo off
rem First, get the locality-invariant datetime
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
rem echo %datetime%

rem Build the reverse date string YYYY-MM-DD
set rdate=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2%
echo rdate=%rdate%

rem Built a datetime string YYYY-MM-DD-hhmmss
set logtime=%rdate%-%datetime:~8,6%
echo logtime=%logtime%


답변

NET TIME \\%ComputerName%대신에 사용해 보셨습니까 DATE? NET TIME로케일에 관계없이 데이터를 일관된 형식으로 제공해야 한다고 생각합니다 .


답변

VS 2008이 배치 파일을 출력하는 것이 맞지만 Powershell 스크립트 및 기타 프로그램을 포함하여 원하는 모든 프로그램을 실행할 수 있습니다.

편집하다:

비슷한 질문이 있습니다.

https://stackoverflow.com/questions/1051845/visual-studio-2008-professional-build-process
https://stackoverflow.com/questions/3049369/embed-application-compilation-time-stamp

원래는 이것을 SO로 옮길 예정이었습니다. . .


답변

이것은 다소 주제가 아닐 수도 있지만 여기에 내가 예약 한 백업을 위해 작성한 .bat 파일이 있으며 Visual Studio의 빌드 후 작업에서 호출합니다. 나는 그것이 도움이되기를 바랍니다.

다음을 .bat 파일에 저장하십시오.

--------------------------------------------------
**:: The following is Copyright © 2012 ShopNetNuke Corp.  All rights reserved.
::  and released under the GNU General Public License (GPLv3)**

:: The following section retrieves the current date and time and formats it into the '%var%' variable
:: This format always ensures that the Date and Time are fixed length to avoid the situation of
:: having a value of '12/ 1/2012 rather than '12/01/2012'
echo off
for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%-%date:~4,2%-%date:~7,2%-%%d-%%e
set var=%var: =0%
echo Beginning my valuable Backup Set:  Backup--%var%

:: If you wanted to request the user input a filename prefix,
:: then we would use something similar to this
:: set /p nameprefix= Enter the file name prefix?
:: Get the Current Date and Time
::for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%-%date:~4,2%-%date:~7,2%-%%d-%%e
:: set var=%var: =0%
:: echo Beginning my valuable Backup Set:  Backup--%var%_%nameprefix%

Pause

echo Starting SQL Server Database Backup Job...
:: The following line initiates the Backup job within SqlServer Agent.
:: Change 'MyBackupNameInSqlAgent' to the name of the job you want executed
:: Change the directory paths to those relevant to your current system installation directories
:: SqlAgent will not return a value if the backup action succeed,
:: however, in the event an error is encountered, it will be echoed onto the screen
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd.exe" -S SQLSERVERNAME\INSTANCENAME -Q "execute msdb.dbo.sp_start_job @job_name = 'MyBackupNameInSqlAgent'"
:: An error will be returned if the Backup job is not found or has already been triggered by another process

echo Starting My Valuable Source Code Directory Backup...

echo ...backing up files and folders in "C:\Source\MyPreciousProjectDirectory\"...
:: The following line will execute the 7zip command to create a .7z file of the directory named in 'MyPreciousProjectDirectory'
:: and tells it to put the archive in the 'MyPreciousBackupDirectory'.  The compression level will be defined by the 7zip default settings
:: The -p flag tells 7zip to password protect the archive, in this case, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectory\%var%\MyPreciousProject--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\*

echo Source Code Directory Backups complete.

echo Archiving Database Backups now...
:: The following line will execute the 7zip command to archive the Database backup.
:: The '*' could be replaced by the actual backup name.
:: The '*' indicates all files of type '.bak'
:: The -p flag tells 7zip to password protect the archive, in this case, again, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z  C:\MyPreciousBackupDirectory\%var%\MyPreciousProject-Database-%var%.7z -p%var% -mhe "C:\Program Files\Microsoft SQL Server\MSSQL10.SQLDEV08\MSSQL\Backup\*.bak"

echo Database Backup Archival process complete.

:: If you wanted to place both the previous backups into one single combination archive,
:: you could do something like the following
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var%\MyPreciousProjectBackupSourceAndDatabase--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\*


echo Now attempting to copy archives to Network Server...
:: The following line will use xcopy to copy the arechives to the server backup directory and place them in a directory named by the DateTime variable %var%
xcopy /S /I /J /Y C:\MyPreciousBackupDirectory\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%
:: Or if the combination above was used then copy that...
xcopy /S /I /J /Y C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%


echo 7z Archive files transferred to MyPreciousBackupServerName successfully
echo  ||
echo \||/
echo  \/
echo ---------------------------------------------------
echo ----- BACKUP SET "%var%" COMPLETE ------
echo ---------------------------------------------------
pause