简体   繁体   中英

How do I get unique email address and retain other fields

$AllMeetUsers = $null
[array]$AllMeetUsers = gam report meet user all | ConvertFrom-Csv | Select-Object 'actor.email','id.time'

[array]$result = $AllMeetUsers | ForEach-Object {
    $Email = $_.'actor.email'
    If (-not([string]::IsNullOrWhiteSpace($Email))) {
        $IDTime = $_.'id.time'
        $FormatIDTime = Get-date($IDTime) -Format("MM-dd-yy")

        [PSCustomObject]@{
            Email = $Email
            Time  = $FormatIDTime
        }
    }
}

Makes an output table like the following

06-07-21 <Email>
09-29-21 <Email>
06-15-21 <Email>
07-12-21 <Email>
07-20-21 <Email>
07-14-21 <Email>

I would like to remove the full duplicate email address line.

but this line is not working

[array]$result = $result  | Sort-Object -Property email | Select-Object time,email -Unique

and

[array]$result = $result  | Sort-Object -Property email | Select-Object email -Unique

removes the time field while giving me unique email addresses.

How do I accomplish this?

Use a Dictionnary @{} instead of an array.

$results = @{}
if (-not $results.ContainsKey($Email)) {
  $results.Add($Email, [PSCustomObject]@{
            Email = $Email
            Time  = $FormatIDTime
   })
}

$results.Values

@MathiasR.Jessen made a good point in the comments and I think my code probably needs a conceptual change. However with the answer I accepted from @Hazrelle above this is how the code came out.

$AllMeetUsers = $null
[array]$AllMeetUsers = gam report meet user all | ConvertFrom-Csv | Select-Object 'actor.email','id.time'

$results = @{}
$AllMeetUsers | ForEach-Object {
    $Email = $_.'actor.email'
    if (-not $results.ContainsKey($Email) -and -not([string]::IsNullOrWhiteSpace($Email))) {
        $IDTime = $_.'id.time'
        $FormatIDTime = Get-date($IDTime) -Format("MM-dd-yy")

        $results.Add($Email, [PSCustomObject]@{
                Email = $Email
                Time  = $FormatIDTime
            })
    }
}
$results.values

For more information. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_hash_tables?view=powershell-7.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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