Comparing folders and content with PowerShell

OK, I’m not going to code the whole thing for you (what’s the fun in that?) but I’ll get you started.

First, there are two ways to do the content comparison. The lazy/mostly right way, which is comparing the length of the files; and the accurate but more involved way, which is comparing a hash of the contents of each file.

For simplicity sake, let’s do the easy way and compare file size.

Basically, you want two objects that represent the source and target folders:

$Folder1 = Get-childitem "C:\Folder1"
$Folder2 = Get-childitem  "C:\Folder2"

Then you can use Compare-Object to see which items are different…

Compare-Object $Folder1 $Folder2 -Property Name, Length

which will list for you everything that is different by comparing only name and length of the file objects in each collection.

You can pipe that to a Where-Object filter to pick stuff that is different on the left side…

Compare-Object $Folder1 $Folder2 -Property Name, Length | Where-Object {$_.SideIndicator -eq "<="}

And then pipe that to a ForEach-Object to copy where you want:

Compare-Object $Folder1 $Folder2 -Property Name, Length  | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {
        Copy-Item "C:\Folder1\$($_.name)" -Destination "C:\Folder3" -Force
        }

Leave a Comment