Quantcast
Viewing all articles
Browse latest Browse all 120

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? Image may be NSFW.
Clik here to view.
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 Image may be NSFW.
Clik here to view.
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” Image may be NSFW.
Clik here to view.
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 Image may be NSFW.
Clik here to view.
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 Image may be NSFW.
Clik here to view.
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 Image may be NSFW.
Clik here to view.
:-D

 


Viewing all articles
Browse latest Browse all 120

Trending Articles