在Powershell中查找文件副本的脚本

时间:2017-06-04 10:17:32

标签: powershell hash

我正在尝试在PowerShell中创建一个脚本来分析recursevily一个目录,并从所有文件和所给出的第一个目录中的所有目录中的所有文件中获取所有哈希值。

之后,我想比较彼此之间的所有哈希,看看哪一个是副本,然后给出一个删除这些副本的选项。

目前我有这个:

$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse
$someFilePath = $UserInput
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
$hash

主要问题在于哈希部分,我在调用" ReadAllBytes"时遇到错误。

我也怀疑是否创建一个数组,所以当我比较哈希时,如果它们相等,则将副本放在一个数组中,这样删除它们就会更容易"。

你怎么看? (我也不确定我是否正确使用" SomeFilePath",MD5或Hash)。

3 个答案:

答案 0 :(得分:3)

如果在Windows 10上定位PowerShell 5.1,我会使用Get-FileHash cmdlet,然后使用Group-Object cmdlet通过哈希对它们进行分组:

$UserInput = Read-Host
$DuplicateFiles = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $DuplicateFiles)
{
    Write-Host "These files share hash $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
}

答案 1 :(得分:1)

试试这个:

$fileHashes = Get-ChildItem -Path $myFilePath -Recurse -File | Get-Filehash -Algorithm MD5
$doubles = $fileHashes | Group hash | ? {$_.count -gt 1} | % {$_.Group} 

foreach($item in $doubles) {
  Write-Output $item
}

答案 2 :(得分:0)

就这样做

Get-ChildItem -Path $UserInput -Recurse -File | Get-FileHash | Group Hash | Where Count -gt 1

简短版本:

gci -Path $UserInput -R -File | Get-FileHash | Group Hash | ? Count -gt 1