如何在批处理脚本中将日期和时间插入文件名?
How to insert date and time to a filename in a batch script?
我为编译“.net”代码的 Jenkins 作业编写了一个批处理脚本,其中一个步骤是在提取新的编译代码之前备份当前目录。
我正在使用这些行来提取要插入到备份文件名中的日期和时间:
for /F "tokens=2-4 delims=/ " %%i in ('date /t') do set date=%%k%%i%%j
for /f "tokens=1-2 delims=/:" %%a in ('time /t') do set time=%%a%%b
powershell.exe -nologo -noprofile -command "& { Add-Type -A System.IO.Compression.FileSystem; [IO.Compression.ZipFile]::CreateFromDirectory('bin', 'bin-%date%_%time%.zip'); }"
xcopy bin-%date%_%time%.zip c:\temp
问题出在 time /t
的输出上,看起来像这样:
01:00 AM
这导致文件名为:
bin-20170412-0100 AM.zip
这是个问题。
我想省略时间变量中的“AM”,怎么办?
因为您显然对 powershell 的使用没有任何问题,所以将前两行替换为:
For /F %%A In ('Powershell -C "Get-Date -Format yyyyMMdd_HHmm"'
) Do Set "archive=bin-%%A.zip"
然后您可以在变量 %archive%
中设置完整的存档文件名,以便在您的后续命令中使用。
我为编译“.net”代码的 Jenkins 作业编写了一个批处理脚本,其中一个步骤是在提取新的编译代码之前备份当前目录。
我正在使用这些行来提取要插入到备份文件名中的日期和时间:
for /F "tokens=2-4 delims=/ " %%i in ('date /t') do set date=%%k%%i%%j
for /f "tokens=1-2 delims=/:" %%a in ('time /t') do set time=%%a%%b
powershell.exe -nologo -noprofile -command "& { Add-Type -A System.IO.Compression.FileSystem; [IO.Compression.ZipFile]::CreateFromDirectory('bin', 'bin-%date%_%time%.zip'); }"
xcopy bin-%date%_%time%.zip c:\temp
问题出在 time /t
的输出上,看起来像这样:
01:00 AM
这导致文件名为:
bin-20170412-0100 AM.zip
这是个问题。
我想省略时间变量中的“AM”,怎么办?
因为您显然对 powershell 的使用没有任何问题,所以将前两行替换为:
For /F %%A In ('Powershell -C "Get-Date -Format yyyyMMdd_HHmm"'
) Do Set "archive=bin-%%A.zip"
然后您可以在变量 %archive%
中设置完整的存档文件名,以便在您的后续命令中使用。