0

我想比较两个对象并只获得不同的值。我有这个代码:

$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

4

3 回答 3

3

Compare-Object 适用于整个对象及其属性。它不会进行惰性字符串匹配。如果你想要你需要先将字符串拆分成数组

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

注意区分大小写的潜在问题并-CaseSensitive根据需要使用。

于 2018-11-23T16:09:00.157 回答
2

对于这个具体的例子:

$a = ("this is blah blah DOG").Split(" ")
$b = ("Dit is blah BLAH dog").Split(" ")
Compare-Object -ReferenceObject $a -DifferenceObject $b
于 2018-11-23T16:10:59.563 回答
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       <=  
#>

最后,这听起来也像这个问答

比较 Powershell 中的两个列表

于 2018-11-24T01:52:01.247 回答