使用PowerShell过滤CSV中的非重复项

pw9qyyiw  于 2022-12-06  发布在  Shell
关注(0)|答案(2)|浏览(102)

我想比较两个csv文件中的值,并返回source 2中与source 1中的条目不匹配的任何条目,同时忽略任何重复的条目。下面是我的尝试,但它没有返回所有条目。让此脚本执行所需操作的最佳方法是什么?

$AD = Import-CSV -Path "source1.csv"
$Student = Import-CSV -Path "source2.csv"

$AD |OuterJoin-Object $Student -on UserPrincipalName | Export-CSV -Path "Path.csv"

Source 1和Source 2 csv包含“Name”、“UserPrincipalName”和“TeamDesc”列。我希望使用这些列来匹配条目。理想情况下,输入/输出如下所示:

Source1.csv
| TeamDesc | UserPrincipalName   |   Name      |
|:---------|:--------------------|:------------|
| Team 1   | student1@domain.com | john smith  |
| Team 1   | student2@domain.com | nancy drew  |
| Team 2   | student3@domain.com | harvey dent |

Source2.csv
| TeamDesc |  UserPrincipalName  |   Name      |
|:---------|:--------------------|:------------|
| Team 1   | student1@domain.com | john smith  |
| Team 2   | student3@domain.com | harvey dent |

Export.csv
| TeamDesc | UserPrincipalName   |  Name      |
|:---------|:--------------------|:-----------|
| Team 1   | student2@domain.com | nancy drew |
aydmsdu9

aydmsdu91#

不确定如何使用OuterJoin-Object。我假设您希望这样做:

$AD = Import-Csv source1.csv | Group-Object UserPrincipalName -AsHashTable -AsString
$Student = Import-CSV -Path source2.csv

@(
    $AD.Values.ForEach{ $_ }
    $Student.Where{ -not $AD.ContainsKey($_.UserPrincipalName) }
) | Export-CSV -Path Path.csv -NoTypeInformation

如果您想排除来自source2.csv的可能重复项,可以使用以下命令:

@(
    $AD.Values.ForEach{ $_ }
    $Student.Where{ -not $AD.ContainsKey($_.UserPrincipalName) }.
        ForEach{ $AD[$_.UserPrincipalName] = $null }
) | Export-CSV -Path Path.csv -NoTypeInformation

现在看一下您经过编辑的答案,它提供了预期的输出,您实际想要的似乎是:

$set = [System.Collections.Generic.HashSet[string]]::new(
    [string[]] (Import-CSV -Path stundent.csv).UserPrincipalName,
    [System.StringComparer]::InvariantCultureIgnoreCase
)
Import-Csv ad.csv | Where-Object { $set.Add($_.UserPrincipalName) } |
    Export-Csv path\to\output.csv -NoTypeInformation
jjjwad0x

jjjwad0x2#

第一个
请注意,UserPrincipalName有两个值,一个来自左表,另一个来自右表(空)。这将显示缺少信息的一侧。您还可以使用-Name参数进一步区分属性,例如:

$Source1 |OuterJoin $Source2 -On Name,TeamDesc -Name Source1,Source2

TeamDesc Source1UserPrincipalName Source2UserPrincipalName Name
-------- ------------------------ ------------------------ ----
Team 1   student2@domain.com                               nancy drew

或仅左侧属性:

$Source1 |OuterJoin $Source2 -On Name,TeamDesc -Property 'Left.*'

TeamDesc UserPrincipalName   Name
-------- -----------------   ----
Team 1   student2@domain.com nancy drew

相关问题