PowerShell : Comparing Contents of Two Folders

Someone at work asked me if I knew a quick way in PowerShell to compare the contents of two folders. I asked a few questions and it turned out he was trying to rationalize all the music folders he had scattered round on his families computers. He wanted a way to look at all the files in a folder and check if an identical file (by identical he meant the same size) was present in a second folder.

I quickly thrashed out a line which he later said did the trick;

gci c:\source | %{$Found=$false;foreach($Item2 in $(
gci d:\target)){if($_.Name -eq $Item2.Name -and
$_.Length -eq $Item2.Length){$Found=$true}};
if (-not $Found){"$($_.Name) not matched."}}

Explanation about how it works below the line.
Continue reading “PowerShell : Comparing Contents of Two Folders”