Bash Folders & files compare === ###### tags: `Power Shell` ### PowerShell 學習 [PowerShell v7.2 官方文件](https://docs.microsoft.com/zh-tw/powershell/scripting/samples/sample-scripts-for-administration?view=powershell-7.2) [檔案同步](https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/390183/) ### 如何執行 PowerShell [設定執行環境](https://medium.com/edward-hong-%E6%8A%80%E8%A1%93%E7%AD%86%E8%A8%98/powershell-%E5%A6%82%E4%BD%95%E6%92%B0%E5%AF%AB%E4%BB%A5%E5%8F%8A%E5%9F%B7%E8%A1%8C-powershell-script-51b6fc7cf099) ### 時間比對 ```bash= get-childitem -Path $Source -Recurse | where-object {$_.LastWriteTime -gt (get-date).addDays(-1)} | where-object {-not $_.PSIsContainer} | Foreach-Object { $_.FullName } | ``` ### 時間比對測試 ```bash= get-childitem -Path $Dest -Recurse | where-object {$_.lastwritetime -gt (get-date).addDays(-1)} | Sort-Object -Property Name,LastWriteTime ``` ### 同步資料夾 ```bash=0 #分別定義源、目標資料夾,注意大小寫敏感 $Source = "G:\folder1" $Dest = "G:\folder2" #遍歷原始檔夾下所有檔案 $folders_a = gci $Source -Recurse | where-object {$_.lastwritetime -gt (get-date).addDays(-5)} foreach ($folder_a in $folders_a) { #通過替換的方式,取目標檔案的全路徑名稱 $b = $folder_a.fullname.replace($Source,$Dest) #判斷目標檔案是否存在,如果存在則先判斷新舊 If (test-path $b) { #判斷目標是否為目錄,如果是目錄則跳過,如果不跳過,則會建立一級空目錄 If (!((gi $b).PSIsContainer)) { #判斷目標檔案、原始檔的新舊情況,如果目標已存在檔案的修改時間早於原始檔,則重新拷貝覆蓋 If ((gci $b).lastwritetime -lt $folder_a.lastwritetime) { copy-item $folder_a.fullname $b -force } } } #如果目標檔案不存在,則直接拷貝 Else { copy-item $folder_a.fullname $b } } ``` ```bash=0 $Source = "G:\folder1" $Destination = "G:\folder2" $SrcObj = Get-ChildItem $Source -Dir | Sort-Object -Property Name,LastWriteTime $DestObj = Get-ChildItem $Destination -Dir | Sort-Object -Property Name,LastWriteTime Tree $Source ``` ```bash=0 $Source = "G:\folder1" $Destination = "G:\folder2" $SrcObj = Get-ChildItem $Source -Dir | Sort-Object -Property Name,LastWriteTime $DestObj = Get-ChildItem $Destination -Dir | Sort-Object -Property Name,LastWriteTime Compare-Object -Ref $SrcObj -Diff $DestObj -Property Name | Where-Object SideIndicator -eq '<=' | New-Item -ItemType Directory -Path {Join-Path $Destination $_.Name} -WhatIf $SrcObj = Get-ChildItem $Source -Dir $DestObj = Get-ChildItem $Destination -Dir Compare-Object -ReferenceObject $Source -DifferenceObject $DestObj -Property Name | Sort-Object -Property Name ``` ### 檔案判斷 [file Management](https://officeguide.cc/windows-powershell-file-folder-management/) [Compare](https://www.tutorialspoint.com/how-to-use-compare-object-in-powershell)