我必须将旧的重复文件移动到另一个目录,同时保留每个原始文件名的最新副本。我需要将它们在该位置保留一周,然后将其删除。我的删除项目已经可以工作,只需要一些关于移动旧重复项的指导。
示例
C:\Temp
text1.txt. 14:03 PM
text2.txt. 14:03 PM
txt1.csv 14:04 PM
C:Temp\Source
text1.txt. 14:01 PM
text2.txt. 14:04 PM
txt1.csv 14:06 PM
目标是将较旧的文件写入 D:\,同时保持结构相同,以避免将来与其他文件发生覆盖错误
D:\Temp
txt1.csv 14:04 PM
text2.txt. 14:03 PM
D:\Temp\SourceDropped
text1.txt. 14:01 PM
结果结果 并拥有 C:\ 现在像这样
C:\Temp
text1.csv 14:03 PM
C:Temp\Source
text2.txt. 14:04 PM
txt1.csv 14:06 PM
我已经尝试过这个,但移动项目没有移动它们
$dirC = 'C\Temp'
$dirD = 'D:\Temp'
Get-ChildItem -Path $dirC -Recurse -File |
Select-Object -Property FullName, Name, LastWriteTime|
Group-Object -Property LastWriteTime |
Where-Object -Property Count -GT 1 |
ForEach-Object {
$_.Group |
Sort-Object -Property LastWriteTime -Descending |
Select-Object -Skip 1 |
Move-Item $_.FullName $dirD -Force #-WhatIf
}
还尝试对它们进行哈希处理,但复制过来时它不遵循结构
$dirC = 'C\Temp'
$dirD = 'D:\Temp'
$hash = @{}
Get-ChildItem -Path $dirC -Recurse -File | ForEach-Object {
$filepath = $_.FullName
$filehash = Get-FileHash -Path $filepath -Algorithm SHA256 |
Select-Object -ExpandProperty Hash
if($hash.ContainsKey($filehash)){
Move-Item -Path $filepath -Destination $dirD -Force
}
}
这可能会帮助您开始,本质上,第一组按其
.Length
归档,以避免不必要的散列它们的开销。然后,如果组中有超过 1 个文件,它将通过 MD5 哈希对它们进行分组,并且只有当文件具有相同的哈希时,它才会按 .LastWriteTime
排序并跳过最新的文件,其余的应移至 $dirD
.
一旦您确认代码正在执行您需要的操作,就应删除 -WhatIf
。
Get-ChildItem $dirC -File -Recurse | Group-Object Length | ForEach-Object {
if ($_.Count -eq 1) {
# nothing to do with a single file, no filehash needed
return
}
# if the group has more than 1 file, get their hash
$groupByHash = $_.Group | Group-Object { ($_ | Get-FileHash -Algorithm MD5).Hash }
# if 2 or more files have the same hash
if ($groupByHash.Count -gt 1) {
# sort by LastWriteTime and skip the last file (the newest)
$groupByHash.Group |
Sort-Object LastWriteTime |
Select-Object -SkipLast 1
}
} | Move-Item -Destination $dirD -WhatIf