我想比较两个对象并仅获取不同的值。我有以下代码:
$a = ("this is blah blah DOG")
$b = ("Dit is blah BLAH dog")
Compare-Object -ReferenceObject $a -DifferenceObject $b
使用上面的代码,我得到以下输出:
InputObject SideIndicator
----------- -------------
Dit is blah BLAH dog =>
this is blah blah DOG <=
但是我只想在两个对象中使用不同的值,例如Dit和this
答案 0 :(得分:3)
Compare-Object
适用于整个对象及其属性。它不会执行惰性字符串匹配。如果您需要先将字符串分成数组
$a = "this is blah blah DOG".Split()
$b = "Dit is blah BLAH dog".Split()
Compare-Object -ReferenceObject $a -DifferenceObject $b
当心与大小写有关的潜在问题,并根据需要使用-CaseSensitive
。
答案 1 :(得分:2)
对于此特定示例:
$a = ("this is blah blah DOG").Split(" ")
$b = ("Dit is blah BLAH dog").Split(" ")
Compare-Object -ReferenceObject $a -DifferenceObject $b
答案 2 :(得分:0)
您没有显示csv文件的外观,因此就可以了,但是逐步执行操作即可。
($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 <=
#>
最后,听起来也像这样的问答环节