比较两个包含Powershell中对象的列表

时间:2018-11-09 08:48:32

标签: powershell class compare

我在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())
    }    
}

我有两个包含来自不同来源的groupObject的ArrayList。

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

1 个答案:

答案 0 :(得分:1)

是的,比较对象就是答案:使用PowerShell代码,您可以添加:

filter_record      service   product
------------------------------------
 500                500       234
 456                600       555
 789                900       757

这将是结果:

$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
相关问题