powershell - Powershell Speed:如何加快 ForEach-Object MD5/哈希检查
问题描述
我正在对 5 亿个文件运行以下 MD5 检查以检查重复项。脚本需要永远运行,我想知道如何加快它。我怎样才能加快速度?当哈希已经存在时,我可以使用 try catch 循环而不是 contains 来引发错误吗?大家会推荐什么?
$folder = Read-Host -Prompt 'Enter a folder path'
$hash = @{}
$lineCheck = 0
Get-ChildItem $folder -Recurse | where {! $_.PSIsContainer} | ForEach-Object {
$lineCheck++
Write-Host $lineCheck
$tempMD5 = (Get-FileHash -LiteralPath $_.FullName -Algorithm MD5).Hash;
if(! $hash.Contains($tempMD5)){
$hash.Add($tempMD5,$_.FullName)
}
else{
Remove-Item -literalPath $_.fullname;
}
}
解决方案
正如评论中所建议的,您可能会考虑仅在与首先找到的文件长度匹配时才开始散列文件。这意味着您不会为任何唯一的文件长度调用昂贵的哈希方法。
*注意:该Write-Host
命令本身非常昂贵,因此我不会显示每次迭代(Write-Host $lineCheck
),但仅在找到匹配项时显示。
$Folder = Read-Host -Prompt 'Enter a folder path'
$FilesBySize = @{}
$FilesByHash = @{}
Function MatchHash([String]$FullName) {
$Hash = (Get-FileHash -LiteralPath $FullName -Algorithm MD5).Hash
$Found = $FilesByHash.Contains($Hash)
If ($Found) {$Null = $FilesByHash[$Hash].Add($FullName)}
Else {$FilesByHash[$Hash] = [System.Collections.ArrayList]@($FullName)}
$Found
}
Get-ChildItem $Folder -Recurse | Where-Object -Not PSIsContainer | ForEach-Object {
$Files = $FilesBySize[$_.Length]
If ($Files) {
If ($Files.Count -eq 1) {$Null = MatchHash $Files[0]}
If ($Files.Count -ge 1) {If (MatchHash $_) {Write-Host 'Found match:' $_.FullName}}
$Null = $FilesBySize[$_.Length].Add($_.FullName)
} Else {
$FilesBySize[$_.Length] = [System.Collections.ArrayList]@($_.FullName)
}
}
显示找到的重复项:
ForEach($Hash in $FilesByHash.GetEnumerator()) {
If ($Hash.Value.Count -gt 1) {
Write-Host 'Hash:' $Hash.Name
ForEach ($File in $Hash.Value) {
Write-Host 'File:' $File
}
}
}
推荐阅读
- flutter - 闪屏出现延迟
- python - 将 Glob.glob 文件转换为 pandas 数据框并附加到 Excel 工作表
- ibm-mq - IBM MQ8 与 JBoss EAP 7.0 兼容吗?
- mongodb - 将scrapy容器连接到mongo容器
- sql - 按嵌套查询排序
- function - GoogleScript - 从 Google 工作表通过电子邮件发送非空白值 - OnFormSubmit
- android - 如何从 googlemap 地址中获取“城市名称”?
- javascript - 有没有办法通过指定您不想发送任何浏览器数据来发送跨域请求?
- apache-spark - 如何使用 Dataset 在 Java Spark 中表示平面图
- django - Django 和 celery DatabaseError: DatabaseWrapper