Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Windows 綜合教學 >> 關於 Windows

Windows Server 自動備份資料批次檔:定時備份遠端主機並自動清理舊檔

編輯:關於 Windows
 

運維常見需求:定時將指定資料備份至遠端主機,並自動刪除 N 天前的舊備份。以下批次檔結合 xcopy/robocopy 與日期運算,搭配 Windows 工作排程器即可無人值守執行。

核心邏輯

  1. 設定保留天數 k=3
  2. 偵測作業系統版本 (2000/XP/2003/Win7) 解析 %date% 格式差異
  3. 計算「今天」與「k 天前」日期,處理閏年、跨月、跨年邊界
  4. 執行備份指令
  5. 刪除遠端/本地備份目錄下符合「k 天前」日期格式的資料夾/檔案

關鍵程式碼片段

:: 設定保留天數
set k=3

:: 判斷 OS 類型解析日期
ver | find /i "5.0." >nul && goto 2000
ver | find /i "5.1." >nul && goto xp
ver | find /i "5.2." >nul && goto xp
ver | find /i "6.1." >nul && goto xp

:2000
set dn=%date:~4,4% & set dy=%date:~9,2% & set dr=%date:~12,2% & goto jc
:xp
set dn=%date:~0,4% & set dy=%date:~5,2% & set dr=%date:~8,2% & goto jc

:jc
:: 閏年/平年判斷邏輯 ...
:: 計算 k 天前日期 (dys/dr) ...
:: 執行 xcopy/robocopy 備份 ...
:: 刪除舊備份: if exist \\remote\backup\%dys%-%dr% rd /s /q \\remote\backup\%dys%-%dr%

部署方式

  1. 存為 auto_backup.bat
  2. 工作排程器 → 建立基本工作 → 每日固定時間觸發 → 動作:啟動程式 auto_backup.bat → 最高權限執行

批次檔完整版較長,建議依實際路徑調整備份來源/目的地與日期格式後投入生產環境。

Copyright © Windows教程網 All Rights Reserved