【问题标题】:compare two lists containing objects in Powershell在 Powershell 中比较两个包含对象的列表
【发布时间】:2018-11-09 08:48:32
【问题描述】:

我在 Powershell 中创建了一个如下所示的对象:

Class groupObject{ 
    [string] $Name
    [string] $Domain

    groupObject([string] $inputName, [string] $inputDomain){
        $this.Name = $inputName
        $this.Domain = $inputDomain
    }

    setName([string] $inputName){ 
        $this.Name = $inputName 
    }

    setDomain([string] $inputDomain){ 
        $this.Domain = $inputDomain 
    } 

    [string] getName(){ 
        return $this.Name
    }

    [string] getDomain(){ 
        return $this.Domain
    }

    # Compare two groupObjects.
    [boolean] isEqual([groupObject] $ADgroup){
        return ($ADgroup.getName() -eq $this.getName() -and $ADgroup.getDomai() -eq $this.getDomain())
    }    
}

我有两个 ArrayList,其中包含来自不同来源的 groupObjects。

现在我想比较这两个列表并找到仅在其中一个列表中的所有组。我正在尝试使用类似$onlyList2= $List2 | ?{$List1 -notcontains $_} 的东西。但我不确定如何使用我的groupObjects 来做到这一点。有什么建议吗?

【问题讨论】:

  • 你试过Compare-Object cmdlet吗?

标签: powershell class compare


【解决方案1】:

是的,Compare-Object 就是答案:使用您的 PowerShell 代码,您可以添加:

$ListLeft = @(
    [groupObject]::new('NameLeft1', 'DomainLeft')
    [groupObject]::new('NameBoth1', 'DomainBoth')
)

$ListRight = @(
    [groupObject]::new('NameRight1', 'DomainRight')
    [groupObject]::new('NameBoth1', 'DomainBoth')
)


'Records which are unique in $ListLeft, comparing Name and Domain:'
Compare-Object -ReferenceObject $ListLeft -DifferenceObject $ListRight -Property 'Name','Domain' | Where-Object SideIndicator -EQ '<=' | FT

'Records which are unique in $ListRight, comparing Name and Domain:'
Compare-Object -ReferenceObject $ListLeft -DifferenceObject $ListRight -Property 'Name', 'Domain' | Where-Object SideIndicator -EQ '=>' | FT

这将是结果:

Records which are unique in $ListLeft, comparing Name and Domain:

Name      Domain     SideIndicator
----      ------     -------------
NameLeft1 DomainLeft <=

Records which are unique in $ListRight, comparing Name and Domain:

Name       Domain      SideIndicator
----       ------      -------------
NameRight1 DomainRight =>

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2014-02-08
    • 2019-04-18
    相关资源
    最近更新 更多