【问题标题】:How to compare CSV file in powershell but exclude some fields of the dataset within the compare如何在 powershell 中比较 CSV 文件但在比较中排除数据集的某些字段
【发布时间】:2023-01-18 00:33:19
【问题描述】:

我正在寻找一种方法来比较两个 CSV 文件与 powershell,并仅输出第一个给定 CSV 文件中不同的数据集。 还应该可以排除数据集的某些字段(通过 CSV 的标题字段名称提供)。

CSV 示例(第一个 CSV 文件)

FirstName;LastName;LastUpdate;Mail;City;PostalCode
Max;Mustermann;01.01.2023;test@test.de;Musterstadt;12345
Maxi;Musterfrau;01.01.2022;maxi@test.de;Musterstadt;12345

CSV 示例(第二个 CSV 文件)

FirstName;LastName;LastUpdate;Mail;City;PostalCode
Max;Mustermann;24.12.2023;test@test.de;Musterdorf;54321
Maxi;Musterfrau;12.12.2022;maxi@test.de;Musterstadt;12345

如 CSV 示例所示,CSV 文件 1 和 2 中的第一个数据集不同。 现在,在比较过程中,应忽略“LastUpdate”字段,以便仅使用“FirstName;LastName;Mail;City;PostalCode”字段来比较数据。

比较的返回应该只是完整的数据集,这些数据集与数组中的第一个文件不同。

我尝试了一些不同的东西,但没有像预期的那样工作。 这是我的尝试示例

# Define the file paths
$file1 = "..\file1.csv"
$file2 = "..\file2.csv"

# Read the first file into a variable
$data1 = Import-Csv $file1

# Read the second file into a variable
$data2 = Import-Csv $file2

# Compare the files, ignoring data from the 'LastUpdate' field 
$differences = Compare-Object -ReferenceObject $data1 -DifferenceObject $data2 -IncludeEqual -ExcludeDifferent -Property 'LastUpdate' | Where-Object {$_.SideIndicator -eq '<='} 

# export differences to a CSV file
$differences | Export-Csv -Path "..\Compare_result.csv" -Delimiter ";" -NoTypeInformation

我希望你们能帮助我。 我提前谢谢你

【问题讨论】:

  • 鉴于您显示的数据,我预计 Compare-Object -ReferenceObject $data1 -DifferenceObject $data2 -IncludeEqual -ExcludeDifferent -Property 'LastUpdate' 不会返回任何内容(因为 LastUpdate 值都不同)。你到底在期待什么?如果你想输出差异,然后删除-ExcludeDifferent

标签: powershell csv compareobject


【解决方案1】:

Compare-Object不允许你排除属性比较 -您要比较的任何属性都必须表达积极地, 作为名称数组传递给-Property.

-ExcludeDifferent开关的目的是排除比较不同的对象并且只有与 -IncludeEqual 结合才有意义,因为比较相等的对象是不是默认包含(在 PowerShell (Core) 7+ 中,现在使用 -ExcludeDifferent暗示-IncludeEqual)。

如果使用 -Property,则 [pscustomobject] 输出对象具有只要指定的属性。按原样传递输入对象, 这-PassThru开关必须使用。

  • 传递的对象用 ETS (Extended Type System) .SideIndicator 属性修饰,因此仍然可以根据它们的独特之处进行过滤。
  • 警告:如果 -IncludeEqual 也存在,对于给定的一对比较相等的输入对象,它是(仅)传递的 -ReferenceObject 集合的对象 - 即使 -DifferenceObject 对象在属性中可能具有不同的值不是被比较。

所以:

# Compare the files, ignoring data from the 'LastUpdate' field 
$differences = 
  Compare-Object -ReferenceObject $data1 `
                 -DifferenceObject $data2 `
                 -Property FirstName, LastName, Mail, City, PostalCode `
                 -PassThru | 
  Where-Object SideIndicator -eq '<=' 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2022-01-18
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多