將來源目錄 D:\a 的變更單向同步至目標目錄 D:\b:新檔複製、舊檔覆寫、目標端多出的檔案不刪除(單向增量),保留目錄結構。
# 來源與目標路徑(注意大小寫敏感)
$folder_a_path = "D:\a"
$folder_b_path = "D:\b"
# 遞歸遍歷來源所有檔案
$folders_a = Get-ChildItem $folder_a_path -Recurse -File
foreach ($folder_a in $folders_a) {
# 計算目標端對應完整路徑
$b = $folder_a.FullName.Replace($folder_a_path, $folder_b_path)
if (Test-Path $b) {
# 目標存在:跳過目錄節點(避免建立空目錄)
if (-not (Get-Item $b).PSIsContainer) {
# 比對修改時間:來源較新才覆寫
if ((Get-Item $b).LastWriteTime -lt $folder_a.LastWriteTime) {
Copy-Item $folder_a.FullName $b -Force
Write-Host "Updated: $b"
}
}
}
else {
# 目標不存在:直接複製(含建立中間目錄)
Copy-Item $folder_a.FullName $b -Force
Write-Host "Created: $b"
}
}
Get-ChildItem -Recurse -File:只取檔案,不取目錄節點,簡化判斷。.Replace($src, $dst):字串替換快速映射對應路徑,前提是路徑分隔符一致。PSIsContainer:判斷是否為目錄容器,避免誤以檔案路徑建立空目錄。LastWriteTime 比對:單向同步核心判斷依據,僅在來源較新時覆寫,減少 I/O。Copy-Item -Force:覆寫唯讀、建立父目錄、保留屬性。# 雙向同步邏輯雛形(僅示意)
function Sync-Bidirectional {
param($Source, $Target)
# 1. Source -> Target (同上)
# 2. Target -> Source (反向同樣邏輯)
# 3. 刪除 Target 獨有檔案(可選):
# Compare-Object (gci $Source -Recurse -File) (gci $Target -Recurse -File) -Property FullName -PassThru |
# Where-Object { $_.SideIndicator -eq '=>' } | Remove-Item -Force
}
# 註冊每小時執行一次的排程任務
$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-File "C:\Scripts\Sync-Dirs.ps1"'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Hours 1)
Register-ScheduledTask -TaskName "DirSync_a_to_b" -Action $action -Trigger $trigger -RunLevel Highest
腳本核心僅 20 行,利用 PowerShell 物件管線與 LastWriteTime 比對實現高效增量同步。生產環境建議加入:錯誤重試、詳細日誌、大檔案分塊複製、頻寬限流、排除清單(-Exclude)等企業級特性。