1

我创建了一个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
}
4

1 回答 1

2

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

假设您的自定义对象的属性是值类型字符串的实例(似乎是这种情况),您可以使用它们的属性值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] 请参阅平等比较帮助主题(为 C# 编写,但类似地适用于 PowerShell 的-eq运算符)。

于 2019-04-15T14:25:40.620 回答