这是此常见任务的更一般用法的批处理文件,因为可以将包含要归档的子文件夹的文件夹指定为运行批处理文件的第一个参数。
@echo off
setlocal
set "BackupFolder=C:\Backup"
rem Folder to archive can be optionally specified as parameter.
if "%~1" == "" (
set "FolderToArchive=C:\projects"
) else (
set "FolderToArchive=%~1"
)
rem Check existence of the folder to archive.
if not exist "%FolderToArchive%\*" (
echo.
echo Error: Folder %FolderToArchive% does not exist.
echo.
endlocal
pause
goto :EOF
)
rem Check existence of backup folder and create this folder
rem if not already existing with verification on success.
if not exist "%BackupFolder%\*" (
md "%BackupFolder%"
if errorlevel 1 (
echo.
echo Error: Folder %BackupFolder% could not be created.
echo.
endlocal
pause
goto :EOF
)
)
rem Archive each subfolder in specified or default folder to archive
rem as separate archive with name of folder as archive file name and
rem with current date and an automatically incremented number with at
rem least 2 digits appended to the archive file name to be able to
rem create multiple archives on different days and even on same day.
rem Parent directory path of each subfolder is removed from archive.
rem The name of the subfolder itself is added to each archive. This
rem can be changed by replacing "%%D" with "%%D\" or "%%D\*". Then
rem the files and subfolders of the compressed folder would be added
rem to archive without the name of the compfessed folder.
rem Best compression is used on creating a solid archive with 4 MB
rem dictionary size. All messages are suppressed except error messages.
rem The last modification time of the created archive file is set to
rem date and time of newest file inside the archive.
set "RarError=0"
for /D %%D in ("%FolderToArchive%\*") do (
echo Archiving %%D ...
"%ProgramFiles%\WinRAR\Rar.exe" a -ag_YYYY-MM-DD_NN -cfg- -ep1 -idq -m5 -md4m -r -s -tl -y "%BackupFolder%\%%~nD.rar" "%%D"
if errorlevel 1 set "RarError=1"
)
rem Wait for a key press if an error occurred on creating an archive file.
if "%RarError%" == "1" (
echo.
pause
)
endlocal
有关Rar命令行上使用的开关的详细信息,请在WinRARRar.txt
的程序文件夹中打开文本文件,这是控制台版本的手册,并阅读这些开关的说明。Rar.exe
注意:命令a(添加到存档)在上面的批处理代码中使用,而不是m(移动到存档)。
从批处理文件中使用的手册WinRAR.exe
可以在WinRAR的帮助中找到选项卡Contents下的项目Command line mode。
WinRAR的控制台和 GUI 版本之间的切换列表存在一些差异。例如WinRAR.exe
,还支持创建Rar.exe
不支持的 ZIP 档案。因此支持控制台版本不WinRAR.exe
支持的开关。-af<type>
或者-idq
控制台版本的开关(安静模式)是-ibck
GUI版本的开关(后台运行)。
要了解所使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。
echo /?
endlocal /?
for /?
if /?
md /?
pause /?
rem /?
set /?
setlocal /?
注意:这样的存档也可以通过 WinRAR 完成,方法是在 WinRAR中选择要存档的文件夹,单击工具栏中的添加图标,插入存档名称并启用选项将每个文件放到单独的存档选项卡文件中。上面通过开关定义的批处理文件中使用的其他选项可以在选项卡General、Backup和Time上找到。C:\Backup\