Reputation: 63
I have two directory structures with sub folders and files. I want to delete any files that are duplicates in the second directory. And then remove any empty folders found in the second directory. I think I've got the piping setup correctly, I'm just not sure how to go about removing the files and if the folder is empty, the folder. The issue seems to be that I can't determine the folder structure of the file that was a duplicate in the remove command.
$Folder1 = Get-ChildItem -Path C:\Temp\Folder1 -Recurse
$Folder2 = Get-ChildItem -Path C:\Temp\Folder2 -Recurse
Compare-Object -ReferenceObject $Folder1 -DifferenceObject $Folder2 -IncludeEqual |
Where-Object {$_.SideIndicator -eq "=="} |
ForEach-Object {
Remove-Item "$($_.FullName)"
}
Upvotes: 2
Views: 3542
Reputation: 200303
You're almost there, but the object you want to use is nested in the InputObject
property of the output you get from Compare-Object
.
Change this:
Remove-Item "$($_.FullName)"
into this:
Remove-Item $_.InputObject.FullName
Beware that the duplicates will be removed from the reference object argument (i.e. $Folder1
). If you want them to be removed from $Folder2
you need to switch the arguments:
Compare-Object -ReferenceObject $Folder2 -DifferenceObject $Folder1 -IncludeEqual |
Where-Object ...
Note also that this approach only compares file names, nothing else. If you need to check whether or not files actually are the same you're probably better off generating the file list with robocopy
, as @Bill_Stewart suggested.
$folder1 = 'C:\Temp\Folder1'
$folder2 = 'C:\Temp\Folder2'
& robocopy.exe "$folder2" "$folder1" /s /l /is /xn /xo /xx /xl /njh /njs /ns /nc /ndl /np |
ForEach-Object { $_.Trim() } |
Remove-Item
Again, you need to use the folder from which you want to delete files as the reference for the comparison.
Upvotes: 2