Powershell阵列:HOWTO Dedup输出

时间:2019-01-04 20:19:28

标签: arrays powershell duplicates

当我在contacts.xml上运行此解析器脚本时(每位用户显示一行),我得到了同一数据的多个实例。我只想为同一数据输入一个条目。如何在将数据写入CSV之前对其进行数据删除?

#https://stackoverflow.com/questions/29999682/powershell-parsing-a-text-file
$input = Get-Content $env:USERPROFILE\Downloads\contacts.xml\Downloads\contacts.xml
$array = @()
$input | % {
    $writeobj = $false
    $obj = New-Object System.Object
    if ($_ -match 'email*') {
        $Email = ($_ -split ':')[1]
    }
    if ($_ -match 'FN*') {
        $NAME = ($_ -split ':')[1]
        $writeobj = $true
    }
    if ($writeobj) {
        $obj | Add-Member -Type NoteProperty -Name Email -Value $Email
        $obj | Add-Member -Type NoteProperty -Name Name -Value $NAME
        $array += $obj
    }
    Write-Host $Name, $email
}
$array | Export-Csv -Path C:\scripts\reports\test.csv -NoTypeInformation

我希望这会产生单个条目,但是我会得到重复的条目(它们也不正确排列)。 (是的,我检查了XML文件中的单个条目)

2 个答案:

答案 0 :(得分:0)

Select唯一对象。

$array |
    Select-Object -Property * -Unique |
    Export-Csv -Path 'C:\scripts\reports\test.csv' -NoType

作为旁注,您可能希望避免在循环中附加到数组,因为这样做势必表现不佳。只需将您的ForEach-Object循环直接传递到Export-Csv中即可。

答案 1 :(得分:0)

我知道了。 我撤消了$ obj Add-Member变量*固定顺序的问题),并在FN匹配中添加了另一条“ $ writeobj = $ true ”行,并且不再重复。 那很奇怪还是什么?

#https://stackoverflow.com/questions/29999682/powershell-parsing-a-text-file
$input = Get-Content $env:USERPROFILE\Downloads\contacts.xml $array =
@() $input | % {
    $writeobj = $false
    $obj = New-Object System.Object
    If ($_ -match 'email') {
        $Email = ($_ -split ':')[1]
        $writeobj = $true
    }
    If ($_ -match 'FN') {
        $NAME = ($_ -split ':')[1]
        $writeobj = $true # <-- right here
    }
    If ($writeobj){
        $obj | Add-Member -type NoteProperty -name Email -value **$NAME**
        $obj | Add-Member -type NoteProperty -name Name -value **$Email**
        $array += $obj
    }
    Write-Host $Name, $email } $array | Export-Csv -path C:\scripts\reports\test.csv -NoTypeInformation