craig
craig

Reputation: 26262

Compare two arrays of PsCustomObjects

Is there an easy way to compare two arrays of PsCustomObjects?

Example A (order independent):

$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

Example B (missing value):

$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

Example C (missing property):

$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

Example D (missing record):

$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

Upvotes: 3

Views: 1268

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

You could use Compare-Object and tell it which properties to compare:

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

The properties could even be extracted from one of the expected or actual objects, provided all of them have the same structure:

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

Upvotes: 5

Related Questions