web-dev-qa-db-ja.com

バッチファイルの日付を予測可能な形式で取得する方法は?

バッチファイルで、dateコマンドから月、日、年を抽出する必要があります。したがって、次のコードを使用しました。これは、基本的にDateコマンドを解析して、そのサブ文字列を変数に抽出します。

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

これはすべて素晴らしいですが、このバッチファイルを地域/国の設定が異なるマシンに展開すると、月、日、年が別の場所にあるため失敗します。

日付形式に関係なく、月、日、年を抽出するにはどうすればよいですか?

17
AngryHacker

ソース: 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

enter image description here


方法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)
14
Tex Hex

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%

出力

enter image description here

13
and31415

私はそれがあなたが要求したものと正確に同じではないことを知っていますが、私はLinux dateアプリケーションのWindowsポートをバッチファイル内のコマンドから使用し、その結果を変数に割り当てます。

バッチコマンドのみを使用して確実に日付を取得する方法はまだ見つけていません。

3
Hydaral

このバッチファイルをYYYY-MM-DD形式で使用します。最近のすべてのWindowsバージョンに存在するはずのウィンドウインストルメンテーションツールを使用して、地域設定に依存しない日時文字列を取得します。

パス(例:c:\ windows\rdate.bat)にバッチファイルを保存し、CALL RDATE.BATでアクセスして変数を設定します。または、コードをバッチファイルにコピーします。

この日付形式は、ファイル名とロギングに適しています。正しくソートされます。 logtime変数は、日付と時刻の変数を、YYYY-MM-DD-HHMMSSとして追加します。これは、バッチファイルのアクティビティを2番目の精度で記録するのに適しています。

必要に応じて日付(および時刻)形式を調整します。 REM画面は本番でエコーします。各テキスト選択の2つの数値は、ゼロベースの開始文字インデックスとコピーする文字数です。たとえば、%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%
2
jim birch

以下に示すように、Tex Hexの優れたGetDate.cmdの回答にバリエーションを提供し、代わりにwmicパラメーター "/ format:list"を使用して、値をバッチ変数に直接割り当てたいと思います。先行ゼロを追加するために、各変数を個別に処理する代わりに、別のFORループを使用しました。これは(合計バイト数で)それほど短くも速くもなく、単にそれを行う別の方法です。

@ECHO OFF
REM Defines variables _Year (4 digits), _Month (01-12), _Day (01-31), _DayOfWeek (0=Sun, 1=Mon etc), _Hour (00-23), _Minute (00-59), _Second (00-59)

setlocal EnableDelayedExpansion
FOR /F %%I IN ('WMIC path win32_localtime get Year^,Month^,Day^,DayOfWeek^,Hour^,Minute^,Second /format:list^|FINDSTR "="') DO SET _%%I
FOR /F "tokens=1 delims==" %%I IN ('set _^|FINDSTR /R "^_[DHMS][aoie][^k]*$"') DO SET %%I=0!%%I!&SET %%I=!%%I:~-3!

:: Display the date/time and day of week
ECHO %_Year%-%_Month%-%_Day% %_Hour%:%_Minute%:%_Second% (day %_DayOfWeek%)

注:このコードがアンダースコアで始まる変数名を使用する別のバッチスクリプトに含まれている(またはそこから呼び出された)場合、値を変更する変数が特定の大文字で始まり、その後に特定の小文字が続くことを確認しましたケースの手紙。 (バッチ変数名は大文字と小文字が区別されませんが、デフォルトではFINDSTRが使用されます。)したがって、アンダースコアで始まる変数名を使用する場合は、それらがすべて小文字(またはすべて大文字)であり、すべてが問題ないことを確認してください。

PS。誰かがそれを必要とする場合に備えて、DayOfWeekを含めました。

1
Ronny D'Hoore

VS 2008がバッチファイルを出力することは正しいですが、Powershellスクリプトやその他のプログラムを含む、ほとんどすべてのプログラムを実行できます。

編集:

同様の質問をいくつか次に示します。

https://stackoverflow.com/questions/1051845/visual-studio-2008-professional-build-processhttps://stackoverflow.com/questions/3049369/embed-application-コンパイルタイムスタンプ

もともと、私はこれをSOに移動するつもりでした。 。 。

1
surfasb

これは少し外れたトピックかもしれませんが、ここに私が自分のスケジュールされたバックアップ用に書いた.batファイルがあり、ビジュアルスタジオのポストビルドアクションからも呼び出します。一部のユーザーに役立つと思います。

以下を.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
0
J.C

DATEの代わりにNET TIME \\%ComputerName%を使用してみましたか? NET TIMEは、ロケールに関係なく、一貫した形式でデータを提供することになっていると思います。

0
Kirk

Shekharの投稿のおかげで、これは必要に応じて機能し、時間のパディングはゼロです。

@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 datetimestr=%var: =0%

set logfile=LogFile-%datetimestr%.txt

echo %logfile%

出力:LogFile-20151113-0901.txt

0
Trifused