Victor Zakharov
Victor Zakharov

Reputation: 26414

How can I tell what is different in Compare-Object result?

Given the following sample code (Powershell), which is based on this solution:

$newFiles = @(Get-ChildItem -recurse -path "c:\path1");
$oldFiles = @(Get-ChildItem -recurse -path "c:\path2");
Compare-Object -ReferenceObject $newFiles -DifferenceObject $oldFiles -Property FullName,Length,LastWriteTime

I have SideIndicator to tell whether or not an object with the same property set is present in either sides. But this is usually of little use for production purposes. What I really need is key all objects by FullName and then compare by Length and LastWriteTime (for the above example). If different, be able to tell what exactly is different (Length or LastWriteTime or both), and how exactly (>, <, =). Is it possible with Powershell, using built-in ways?

Upvotes: 0

Views: 10427

Answers (1)

Keith Hill
Keith Hill

Reputation: 201612

Compare-Object is a pretty feature-light cmdlet. It could stand some serious improvements. The best way I could get this to work was to piece out the removed/added files into a separate bucket and then compare just the same files using Name not FullName with a SyncWindow of 1 e.g.:

$removed = Compare-Object -ReferenceObject $oldFiles -DifferenceObject $newFiles -Property Name -PassThru | Where {$_.SideIndicator -eq '<='}
$added = Compare-Object -ReferenceObject $oldFiles -DifferenceObject $newFiles -Property Name -PassThru | Where {$_.SideIndicator -eq '=>'}
$removedNames = $removed | Foreach {$_.Fullname}
$same = $oldFiles | Where {$_.Fullname -notin $removedNames}
Compare-Object -ReferenceObject $same -DifferenceObject $newFiles -Property Name,Length,LastWriteTime -SyncWindow 1

This gave me results like this:

Name                                                 Length LastWriteTime                 SideIndicator
----                                                 ------ -------------                 -------------
AssemblyInfo.Shared.cs                                  340 8/28/2012 1:21:53 AM          =>
AssemblyInfo.Shared.cs                                  340 8/28/2012 1:21:28 AM          <=
EchoArgs.cs                                             825 8/28/2012 1:21:54 AM          =>
EchoArgs.cs                                             825 8/28/2012 1:21:30 AM          <=
AssemblyInfo.cs                                         151 8/28/2012 1:21:54 AM          =>
AssemblyInfo.cs                                         151 8/28/2012 1:21:31 AM          <=

Even so, part way through the listing the files get out of sync. Go figure. If you eliminate the SyncWindow parameter, you still get "correct" results it is just that the files are scattered about and not lined up one under another. :-(

Upvotes: 3

Related Questions