Garrett
Garrett

Reputation: 649

Compare PSCustomObject to Object

I have created a PsCustomObject, when the variable is called is ISE, it reads a table of the relevant data. However, if I try to compare the PsCustomObject with another object, the PsCustomObject doesn't read correctly. I'd like to tell the script if any of the lines in the existing CSV match the PSCustomObject do not export the data to the CSV, in other words skip duplicate rows in the CSV file. The CSV may or may not have multiple rows.

$fileInfo = @(
                        [pscustomobject]@{
                            user_id = $user
                            studio = $studio
                            function = $Task
                            end_time_local = $creationTime
                            asin = $ASIN
                            variant = $variant
                            process_class_id = $processClass
                            }
                           )
$currentData = Import-Csv "$scansFolder\$fileName.csv"
if($fileInfo -ne $currentData){
$fileInfo | Export-Csv "$scansFolder\$fileName.csv" -Append -NoTypeInformation -Force
}

Upvotes: 1

Views: 1229

Answers (1)

mklement0
mklement0

Reputation: 437608

[pscustomobject] is a .NET reference type, so comparing two instances[1] with -eq will test for reference equality (identity), i.e. if the two instances are one and the same object[2] - which is obviously not the case in your scenario.

Assuming that the properties of your custom objects are instances of value types or strings (which appears to be the case), you can use Compare-Object to compare objects by their property values, with the ability to compare two collections:

$fileInfo = @(
  [pscustomobject]@{
      user_id = $user
      studio = $studio
      function = $Task
      end_time_local = $creationTime
      asin = $ASIN
      variant = $variant
      process_class_id = $processClass
      }
)

# Get the property names.
# This assumes that the CSV data has (at least) the same
# set of properties (columns).
$propNames = $fileInfo[0].psobject.properties.Name

$currentData = Import-Csv "$scansFolder\$fileName.csv"

# Compare the $fileInfo custom object(s) to the custom objects read
# from the CSV file and only export those that are unique to the RHS ('=>')
# back to the file, i.e., those that don't match $fileInfo.
Compare-Object -Property $propNames $fileInfo $currentData |
  Where-Object SideIndicator -eq '=>' | Select-Object InputObject | 
    Export-Csv "$scansFolder\$fileName.csv" -Append -NoTypeInformation -Force

[1] Import-Csv outputs [pscustomobject] instances too.

[2] See the Equality Comparison help topic (written for C#, but applies analogously to PowerShell's -eq operator).

Upvotes: 2

Related Questions