檔案夾 X 有很多子檔案夾 A、B、C、D……每個子檔案夾都有很多檔案,我想存檔這些子檔案夾中的所有檔案,并且這些檔案早于 6 個月。之后檢查是否創建了存檔并洗掉已存檔的檔案。
這是我嘗試過的:
#$SourceFolder = "C:\Users\sec\Desktop\X"
ForEach-Object
{
Get-ChildItem -Path "$($_.FullName)" -Exclude "*.zip"
Where-Object {($_.LastWriteTime -lt (Get-Date).AddMonths(-6))} |
Compress-Archive -DestinationPath "$($_.FullName)\06.2020andOlder.zip" -Update;
if (Test-Path 06.2020andOlder.zip) {
Remove-Item -Force
}
}
uj5u.com熱心網友回復:
假設您希望每個子檔案夾都以舊檔案所在的 .zip 存檔結束,請嘗試以下操作:
用于Group-Object將同一子目錄中的所有舊檔案組合在一起,并使用它來創建 .zip 檔案并在壓縮后洗掉原始檔案。
$SourceFolder = 'D:\Test'
$refDate = (Get-Date).AddMonths(-6).Date # take this from midnight
Get-ChildItem -Path $SourceFolder -File -Recurse -Exclude "*.zip" |
Where-Object { $_.LastWriteTime -lt $refDate } |
Group-Object DirectoryName | ForEach-Object {
# construct the target folder path for the zip file using the Name of each group
$zip = Join-Path -Path $_.Name -ChildPath '06.2020andOlder.zip'
# archive all files in the group
Compress-Archive -Path $_.Group.FullName -DestinationPath $zip -Update
# here is where you can delete the original files after zipping
$_.Group | Remove-Item -WhatIf
}
注意我已將 switch 添加-WhatIf到 Remove-Item cmdlet。這是一個安全開關,因此您實際上還沒有洗掉任何內容。該cmdlet現在只顯示什么將被洗掉。一旦您對此輸出感到滿意,請移除該-WhatIf開關,以便洗掉檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/394608.html
上一篇:使用{將元素添加到陣列中?:}
