Nicola Cossu
Nicola Cossu

Reputation: 56357

how can i handle compare-object result?

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?

Upvotes: 10

Views: 33390

Answers (3)

Geoff Duke
Geoff Duke

Reputation: 141

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

Upvotes: 4

stej
stej

Reputation: 29449

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.

Upvotes: 9

ravikanth
ravikanth

Reputation: 25810

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.

Upvotes: 4

Related Questions