我正在寻找一种方法来比较两个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;姓氏;邮件;“城市;邮政编码”将用于比较数据。
比较的返回值应该仅是与数组中的文件一不同且仅与之不同的完整数据集。
我尝试了一些不同的方法,但都没有达到预期的效果。这里是我尝试的样本
# 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
希望你们能帮我一把,先谢谢你们了
1条答案
按热度按时间hsgswve41#
Compare-Object
不允许您 * 排除 * 要比较的属性-您要比较的任何属性都必须 * 肯定地*表示为传递给-Property
的名称数组 。-ExcludeDifferent
开关的用途是 * 排除比较结果不同的对象 ,并且仅在与-IncludeEqual
结合使用时才有意义,因为默认情况下,比较结果相同的对象 * 不 * 包括在内(在PowerShell(Core)7+中,使用-ExcludeDifferent
现在 * 暗示 *-IncludeEqual
)。如果使用
-Property
,则[pscustomobject]
输出对象 * 仅 * 具有指定的属性。要按原样传递输入对象,必须使用-PassThru
开关。.SideIndicator
属性修饰,因此仍然可以根据它们的唯一性进行过滤。-IncludeEqual
也存在,对于给定的一对比较相等的输入对象,(仅)-ReferenceObject
集合的对象被传递--即使-DifferenceObject
对象在 * 没有 * 被比较的属性中可能有不同的值。因此: