Comparing hashes and delete files with same hash in powershell not working

Viewed 2451

I am doing a script that identifies the hashes of all the files of a path (and recursively). This is alright.

My problem comes when, after I have identified which hashes are the same, I want to save them into an array so later I can delete these files that have the same Hash (if I want to), or just print the duplicate files. And I have been all afternoon and evening trying to figure out how to do it. My code at the moment:

Write-Host "Write a path: "
$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse

#Get-FileHash cmdlet to get the hashes
$files = Get-ChildItem -Path $UserInput -Recurse | where { !$_.PSIsContainer }
$files | % {(Get-FileHash -Path $_.FullName -Algorithm MD5)}



#Creating an array for all the values and an array for the duplicates
$originals=@()
$copies=@()

 #grouping the hashes that are duplicated cmdlet Group-Object:
$Duplicates = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $Duplicates)
{
    Write-Host "These files share hash : $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
    $copies+=$Duplicates

}

So the last part "$copies+=$Duplicates" does not work properly.

In the begining I was thinking of saving the first file in the "original" array. If the second one has the same hash, save that 2nd in the "copies" array. But I am not sure if I can do that in the 1st part of the script when getting the hashes.

After that, the second array would have the duplicates, so it would be easy to delete them from the computer.

2 Answers
Related