Home > Software engineering >  How do I get unique email address and retain other fields
How do I get unique email address and retain other fields

Time:10-23

$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?

CodePudding user response:

Use a Dictionnary @{} instead of an array.

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

$results.Values

CodePudding user response:

@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

  • Related