【问题标题】:Compare Object Powershell比较对象 Powershell
【发布时间】:2018-11-24 09:52:01
【问题描述】:

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

$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

【问题讨论】:

    标签: powershell compareobject


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      对于这个具体的例子:

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

      【讨论】:

      • 当我对从 csv 文件导入值的对象执行相同操作时,我会在两个对象中都获得项目。而我只想要在 object1 中但不在 object2 中的项目
      • 建议您发布您想要做的最低限度的精确复制。
      【解决方案3】:

      你没有显示你的 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       <=  
      #>
      

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

      Compare two lists in Powershell

      【讨论】:

        猜你喜欢
        • 2019-04-21
        • 2021-04-06
        • 1970-01-01
        • 2014-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        • 2011-01-26
        相关资源
        最近更新 更多