比较两个PsCustomObjects数组

时间:2017-01-12 16:05:03

标签: powershell

有没有一种简单的方法来比较PsCustomObject的两个数组?

示例A(与订单无关):

$Expected = @()
$Expected += [PsCustomObject]@{Table='patient';ColumnName='id'}
$Expected += [PsCustomObject]@{Table='patient';ColumnName='mrn'}

$Actual = @()
$Actual += [PsCustomObject]@{Table='patient';ColumnName='mrn'}
$Actual += [PsCustomObject]@{Table='patient';ColumnName='id'}

Compare-ByFoo ($Expected $Actual).Count | Should Be 0

示例B(缺失值):

$Expected = @()
$Expected += [PsCustomObject]@{Table='patient';ColumnName='id'}
$Expected += [PsCustomObject]@{Table='patient';ColumnName='mrn'}

$Actual = @()
$Actual += [PsCustomObject]@{Table='';ColumnName='id'}
$Actual += [PsCustomObject]@{Table='patient';ColumnName='id'}

Compare-ByFoo ($Expected $Actual).Count | Should Be 1

示例C(缺少属性):

$Expected = @()
$Expected += [PsCustomObject]@{Table='patient';ColumnName='id'}
$Expected += [PsCustomObject]@{Table='patient';ColumnName='mrn'}

$Actual = @()
$Actual += [PsCustomObject]@{Table='patient'}
$Actual += [PsCustomObject]@{Table='patient';ColumnName='id'}

Compare-ByFoo ($Expected $Actual).Count | Should Be 1

示例D(缺少记录):

$Expected = @()
$Expected += [PsCustomObject]@{Table='patient';ColumnName='id'}
$Expected += [PsCustomObject]@{Table='patient';ColumnName='mrn'}

$Actual = @()
$Actual += [PsCustomObject]@{Table='patient';ColumnName='id'}

Compare-ByFoo ($Expected $Actual).Count | Should Be 1

1 个答案:

答案 0 :(得分:1)

您可以使用Compare-Object并告诉它要比较哪些属性:

@(Compare-Object $Expected $Actual -Property Table, ColumnName |
    Where-Object { $_.SideIndicator -eq '=>' }).Count

甚至可以从预期或实际对象之一中提取属性,只要它们具有相同的结构:

$props = $Expected[0].PSObject.Properties | Select-Object -Expand Name
@(Compare-Object $Expected $Actual -Property $props |
    Where-Object { $_.SideIndicator -eq '=>' }).Count