Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i handle compare-object result?

Tags:

powershell

I made a lot of searches before posting with no luck. Let's suppose I want to compare two folders

compare-object @(gci c:\folder1) @(gci c:\folder2) 

I see the output with sideIndicator and so on but how can I do something like

if objects are equals then
  do something
else
  do something else
end if

if I pipe this cmdlet to get-member I see an equals method but I don't know how to use it and I'm not even sure if it could solve my problem. Is there any boolean property that tells me if objects are equals or not? Thanks for your time.

EDIT

Hi my saviour. :) If I have understood I had to do something like this:

$differences = 0
$a = @(1,4,5,3)
$b = @(1,3,4)
diff $a $b -in | % {if($_.sideindicator -ne "==") {$differences+=1}}
write-host $differences

Is this the only way?

EDIT 2.

It seems to me that if I don't use -includeEqual I get only the differences, so this code suffices.

$differences = 0
$a = @(1,4,5,3)
$b = @(1,3,4)
diff $a $b  | % {$differences+=1}
write-host $differences

and it returns 0 if objects are equals. Is it the right way to solve my problem?

like image 297
Nicola Cossu Avatar asked Apr 27 '11 14:04

Nicola Cossu


3 Answers

Basically, you don't need to count the differences, instead if just finding '==' is enough for you, you might use:

$a = @(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
$b = @(10, 1, 2, 3, 4, 5, 6, 7, 8, 9)
if (diff $a $b) { 
 'not equal'
} else {
 'equal'
}

How it works: if the pipeline (~sequence from diff) returns collection of 0 items, then when converting to [bool], it is converted to $false. Nonempty collection is converted to $true.

like image 92
stej Avatar answered Oct 12 '22 19:10

stej


Take a look at this example: http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2011/01/12/quicktip-Comparing-installed-HotFixes-on-a-two-node-Cluster.aspx

You can use the sideindicator value and do a string compare.

like image 33
ravikanth Avatar answered Oct 12 '22 19:10

ravikanth


If you just want a count of the differences, you can get even more succinct:

$a = 1..10
$b = 3..11
(diff $a $b).count
like image 20
Geoff Duke Avatar answered Oct 12 '22 17:10

Geoff Duke