【发布时间】: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