7-Zip 是一套有用的壓縮工具. 除了GUI 介面外, 還可以透過指令執行. 亦因此部份情況下會利用它進行備份. 在示範中會以指令形式執行備份.
@echo off
REM Get current date / time and split to different variables.
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined currentDate set currentDate=%%x
set year=%currentDate:~0,4%
set month=%currentDate:~4,2%
set day=%currentDate:~6,2%
set hour=%currentDate:~8,2%
set min=%currentDate:~10,2%
set sec=%currentDate:~12,2%
REM Initialize variables.
set zipfilename=%~n1_%year%%month%%day%_%hour%%min%%sec%.zip
set destination=%~dp1
set source="%~1\*"
set dest="%destination%Backups\%zipfilename%"
REM Check 7-Zip installed or not. If not, process will terminated.
set AppExePath="%ProgramFiles(x86)%\7-Zip\7z.exe"
if not exist %AppExePath% set AppExePath="%ProgramFiles%\7-Zip\7z.exe"
if not exist %AppExePath% goto notInstalled
REM Start backup.
echo Backing up %source% to %dest%
%AppExePath% a -r -tzip %dest% %source%
echo %source% backed up to %dest% is complete!
goto end
:notInstalled
echo Can not find 7-Zip, please install it from:
echo http://7-zip.org/
:end
在示範中, 會將指定文件夾備份, 並存放於c:\Backups 中, 叫用方法如下:
Backup.bat c:\BackupFolder
Leave a Reply