比较PSCustomObject和Object

时间:2019-04-15 13:38:18

标签: powershell pscustomobject

我创建了一个PsCustomObject,当调用的变量是ISE时,它将读取相关数据表。但是,如果我尝试将PsCustomObject与另一个对象进行比较,则PsCustomObject无法正确读取。我想告诉脚本是否现有CSV中的任何行与PSCustomObject匹配都不会将数据导出到CSV,换句话说就是跳过CSV文件中的重复行。 CSV可能有也可能没有多行。

$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
}

1 个答案:

答案 0 :(得分:2)

[pscustomobject]是.NET 引用类型,因此将两个实例 [1] -eq进行比较将测试引用是否相等(身份),即,如果两个实例是一个并且是同一对象 [2] -在您的情况下显然不是这种情况。

假设您的自定义对象的 properties 值类型 strings (似乎是这种情况)的实例,则可以使用Compare-Object通过对象的属性值比较对象,并能够比较两个集合

$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也输出[pscustomobject]实例。

[2]请参见Equality Comparison帮助主题(为C#编写,但类似地适用于PowerShell的-eq运算符)。