我一直在使用以下批处理文件来备份Windows服务器机器上的某个目录很长时间。批处理文件由 Windows 计划任务每天在特定时间运行,并在删除最旧的.7z文件 (7z = www.7-zip.org) 后将特定文件夹压缩到备份位置。
这样,我的备份文件夹中只有 BackupNr 中指定的.7z文件数量,而不必手动删除最旧的.7z文件。
问题是"设置 BackupNr=1"行。使用 BackupNr=1,在批处理文件运行后,我的备份文件夹中总是有两个.7z存档。
我无法弄清楚我需要更改什么,以便在批处理文件运行时只保留一个存档。我该如何解决这个问题?
@echo off
:: The name of the backup file that will be created. It will use the current date as the file name.
@For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do @(
Set FileName=%%A%%B%%C%%D
)
:: The name of the folders where all the backup .zip and report files will be stored.
Set ArchiveFolder=D:BackupManualArchives
Set ReportFolder=D:BackupManualReports
:: The name of the folder that will be backed up, i.e. the AppData folder.
Set FolderToBackup=C:AppData
:: The number of .zip files and .txt reports to keep. Older archives will be deleted according to their age. This ensures we only keep the most recent X number of backups.
Set BackupNr=1
:: Delete oldest backup archives so we only keep the number of archives specified in "skip=".
echo.>> DeletedBackups.txt
date /t >> DeletedBackups.txt
echo.>> DeletedBackups.txt
echo These older backups were deleted:>> DeletedBackups.txt
for /F "skip=%BackupNr% delims=" %%a in ('dir /b /o-d %ArchiveFolder%*') do (
echo %ArchiveFolder%%%a%1>> DeletedBackups.txt
del /f /q %ArchiveFolder%%%a%1
)
echo.>> DeletedBackups.txt
echo These older reports were deleted:>> DeletedBackups.txt
for /F "skip=%BackupNr% delims=" %%a in ('dir /b /o-d %ReportFolder%*') do (
echo %ReportFolder%%%a%1>> DeletedBackups.txt
del /f /q %ReportFolder%%%a%1
)
echo Starting the backup: %DATE% %TIME% >> %ReportFolder%%FileName%.txt
:: Adds all files to 7z archive using BCJ2 converter, LZMA with 8 MB dictionary for main output stream (s0), and LZMA with 512 KB dictionary for s1 and s2 output streams of BCJ2.
C:PROGRA~17-Zip7z.exe a -t7z %ArchiveFolder%%FileName%.7z %FolderToBackup%* -m0=BCJ2 -m1=LZMA:d23 -m2=LZMA:d19 -m3=LZMA:d19 -mb0:1 -mb0s1:2 -mb0s2:3 >> %ReportFolder%%FileName%.txt
echo Backup finished at: %DATE% %TIME% >> %ReportFolder%%FileName%.txt
:: Write the backup Start and End times to the BackupInfo.csv file.
gawk -f BackupRecord.awk %ReportFolder%%FileName%.txt >> %ReportFolder%BackupReport.csv
:: Write the file size of the backup .zip file that was just created to the log file.
set size=0
call :filesize %ArchiveFolder%%FileName%.7z
echo Backup archive file size: %size% bytes >> %ReportFolder%%FileName%.txt
exit
:: set filesize of 1st argument in %size% variable, and return
:filesize
set size=%~z1
exit /b 0
谢谢。
dir 命令中的/b 开关不使用标头或摘要。 结果是一个普通的存档列表,在本例中,排序器按创建时间降序排列,最近的第一个。
问题是跳过=%备份Nr%
for /F "skip=%BackupNr% delims=" %%a in ('dir /b /o-d %ReportFolder%*') do (
echo %ReportFolder%%%a%1>> DeletedBackups.txt
del /f /q %ReportFolder%%%a%1
)
跳过第一行,因此删除命令会删除除最新存档之外的所有存档。
然后执行备份,以便将新文件添加到目录中。结果,两个文件。
如果您只想要最后一个,则应首先执行备份并在删除后执行备份,或者从for命令中删除skip=%BackupNr%。