[Batch] 利用7-Zip 進行備份

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)%-Zipz.exe"
if not exist %AppExePath% set AppExePath="%ProgramFiles%-Zipz.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

 

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.