简体   繁体   English

Powershell阵列:HOWTO Dedup输出

[英]Powershell Array: HOWTO Dedup Output

When I run this parser script on my contacts.xml, which shows one line per user, I get multiple instances of the same data. 当我在contacts.xml上运行此解析器脚本时(每位用户显示一行),我得到了同一数据的多个实例。 I only want a single entry for the same data. 我只想为同一数据输入一个条目。 How do I dedup the data before it writes to the CSV? 如何在将数据写入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

I expect this to produce single entries but I get duplicates (and they don't line up right either). 我希望这会产生单个条目,但会得到重复(它们也不正确排列)。 (And yes I checked the XML file for single entries) (是的,我检查了XML文件中的单个条目)

Select the unique objects. 选择唯一的对象。

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

As a side note, you may want to avoid appending to an array in a loop, as that is bound to perform poorly. 附带说明一下,您可能希望避免在循环中附加到数组,因为这样做势必会导致性能下降。 Just pipe your ForEach-Object loop directly into Export-Csv . 只需将您的ForEach-Object循环直接传递到Export-Csv

I figured it out. 我想到了。 I REVERSED the $obj Add-Member variables *that fixed the order) and added another " $writeobj = $true " line to the FN match, and VOILÀ no more dupes. 我撤消了$ obj Add-Member变量*固定顺序),并在FN匹配项中添加了另一条“ $ writeobj = $ true ”行,并且不再重复。 Is that weird or what? 那很奇怪还是什么?

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM