0

I want to compare two objects and get only the different values. I have this code:

$a = ("this is blah blah DOG")
$b = ("Dit is blah BLAH dog")
Compare-Object -ReferenceObject $a -DifferenceObject $b

with the above code I get the following output:

InputObject           SideIndicator
-----------           -------------
Dit is blah BLAH dog  =>           
this is blah blah DOG <=    

However I want only the different values in both the objects i.e. Dit and this

3 Answers 3

3

Compare-Object works on the whole objects and its properties. It will not do lazy string matching. If you wanted that you need to split the string into arrays first

$a = "this is blah blah DOG".Split()
$b = "Dit is blah BLAH dog".Split()
Compare-Object -ReferenceObject $a -DifferenceObject $b

Beware of potential issues with case sensitivity and use the -CaseSensitive as needed.

Sign up to request clarification or add additional context in comments.

Comments

2

For this specific example:

$a = ("this is blah blah DOG").Split(" ")
$b = ("Dit is blah BLAH dog").Split(" ")
Compare-Object -ReferenceObject $a -DifferenceObject $b

2 Comments

When I do the same for an object that imports values from a csv file I get items in both the objects. Whereas I only want items that are in object1 but not in object2
Recommend you post a minimum exact repro of what you are wanting to do.
0

You don't show what your csv file looks like, so, there's that, but stepping though what you are after.

($a = Get-Content -Path 'D:\Documents\file1.txt')
($b = Get-Content -Path 'D:\Documents\file2.txt')
Compare-Object -ReferenceObject $a -DifferenceObject $b

<#
What's in the two files

file1
hello
world



file2
hello
world



InputObject SideIndicator
----------- -------------
file2       =>           
file1       <=           
#>




($a = Get-Content -Path 'D:\Documents\file1.csv')
($b = Get-Content -Path 'D:\Documents\file2.csv')
Compare-Object -ReferenceObject $a -DifferenceObject $b

<#
What's in the two files

Col1,Col2,Col3
file1,hello,world



Col1,Col2,Col3
file2,hello,world



InputObject       SideIndicator
-----------       -------------
file2,hello,world =>           
file1,hello,world <=           
#>



($a = (Get-Content -Path 'D:\Documents\file1.csv' | Select -Skip 1) -split ',')
($b = (Get-Content -Path 'D:\Documents\file2.csv' | Select -Skip 1) -split ',')
Compare-Object -ReferenceObject $a -DifferenceObject $b

<#
file1
hello
world



file2
hello
world




InputObject SideIndicator
----------- -------------
file2       =>           
file1       <=  
#>

Lastly, this also sounds eerily like this Q&A

Compare two lists in Powershell

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.