PowerShell – Having fun with Compare-Object in the 2012 Scripting Games

This year I was competing in the Windows PowerShell Scripting Games 2012.
One of the exercises in the Beginners class was to
compare two folders.
Ed Wilson (Microsoft ScriptingGuy) provided a script to create two folders with a bunch of files in them and delete one file from each folder.

So, I started to script… by using the Compare-Object cmdlet. This lets you compare objects (sounds kinda logical when looking at the name of the cmdlet, right? Knipogende emoticon).

But, then there was the Expert Commentary… here the expert provided explanation of the exercise and the solution. The solution he provided was as follows:

$original = Get-Childitem -Path c:\1 | Sort-Object -Property Name
$copy = Get-Childitem -Path c:\2 | Sort-Object -Property Name
$difference = @(Compare-Object -ReferenceObject $original -DifferenceObject $copy -Property Name -PassThru)
if ($difference.Count -eq 0) {
Write-Host -ForegroundColor Green ‘Content is equal’
} else {
Write-Host -ForegroundColor Red ‘Content is different. Differences:’
$difference
}

Now, this is a easy and good solution Glimlach
In short (by removing code that’s not required for the functionality of the script), this will become something like:

$original = Get-Childitem -Path c:\1 | Sort-Object -Property Name
$copy = Get-Childitem -Path c:\2 | Sort-Object -Property Name
$difference = @(Compare-Object -ReferenceObject $original -DifferenceObject $copy -Property Name -PassThru)

This differs from the solution I came up with since I’m a big fan of “one liners” Verhitte emoticon
My solution:

Compare-Object –ReferenceObject (Get-ChildItem C:\1) –DifferenceObject (Get-ChildItem C:\2) –Passthru

Now, yesterday one of my students (in a PowerShell workshop I’m giving) came up with an even shorter solution (and I was thinking my solution was bad-ass Knipogende emoticon):

Compare-Object (Get-Childitem C:\1) (Get-ChildItem C:\2)

This is because Compare-Object automatically knows that if you provide the objects, the first is the ReferenceObject and the second will be the DifferenceObject… so even an easier way Emoticon met brede lach

Now this is the strength of PowerShell… it’s very easy, short, intelligent and understandable… but you can still make it as complex as you want 😀

 

One comment

  1. Boe Prox says:

    Compare-Object is a great cmdlet and very useful. But there are some gotchas when using it with certain objects. I wrote an article a while back that takes a look at one of those gotchas with comparing objects and not getting the results that one might think they would get. http://learn-powershell.net/2012/01/02/compare-object-weirdness-or-business-as-usual/
    Good job on this article and great job in the Scripting Games this year!

    Boe

Leave a Reply

Your email address will not be published. Required fields are marked *