镜像目录,仅清除目标目录中超过 7 天的文件

镜像目录,仅清除目标目录中超过 7 天的文件

我想要镜像一个目录,但只删除目标目录中超过 7 天的文件。

情况:

- Directory A is mirrored to Directory B.
- A file from Directory A is deleted

我希望该文件在目录 B 中保留 7 天。如果 7 天后该文件在目录 A 中仍不存在,则该文件将被删除。

当前解决方案:

- Use Free File Sync to mirror Directory A to Directory B. Extra files in Directory B are moved (termed versioning within Free File Sync) to a temp directory
- Use a powershell script to update date modified to current date for all files in the temp directory
- Move contents of temp directory to a delete pending directory using robocopy
- Use Delage32 program to delete files and empty directories older (date modified) than 7 days in the delete pending directory.

有两个问题。一是这种备份所需的步骤数量。更重要的是,我必须使用两个具有过多磁盘写入的临时目录才能实现我想要的效果。

如果 robocopy 会更新目标目录中的时间戳,即使没有进行任何复制,我也可以不使用 robocopy /mir 选项和 delage32。就像 robocopy 中整合的 unix touch 命令一样。有什么建议或替代方案吗?

答案1

这是一个简单的 PowerShell 脚本,它将执行您要查找的操作。适当更改FolderAFolderB。此外,-whatif只会告诉您它将执行的操作,而不会执行任何操作。一旦您验证了您要执行的操作是正确的,只需删除即可-whatif

#This sets $FolderA to the directory you want to copy from    
$FolderA = "v:\FolderA"
#This sets $FolderB to the directory you want to copy to
$FolderB = "v:\FolderB" 
#This does the copy (Note the -whatif to make sure this is what you want)
Copy-Item -Path "$FolderA\*" -Destination $FolderB -WhatIf
#This does a compare of Directory A and B, and removes all files that only exist in Directory B that haven't been access for 7 days. (Again, notices the -whatif at the end)
Compare-Object (Get-ChildItem $FolderA) (Get-ChildItem $FolderB) ` #The [`] tells PowerShell the command will continue on the next line
    | where {$_.SideIndicator -eq "=>"} `
    | where {$_.InputObject.LastWriteTime -le (Get-Date).Adddays(-7)} `
    | Foreach { Remove-Item -Path $_.InputObject.FullName -WhatIf}

相关内容