Powershell only recieve uniqe and latest result based on date

Viewed 21

I got a portion of a larget script:

$clientsecrets = @()
$applist = Get-MsolServicePrincipal -all |
           Where-Object -FilterScript {
               ($_.DisplayName -like "*SI*") -or
               ($_.DisplayName -like "*FD*") -or
               ($_.DisplayName -like "*AP*") -and
                   ($_.DisplayName -notlike "*Microsoft*") -and
                   ($_.DisplayName -notlike "autohost*") -and
                   ($_.ServicePrincipalNames -notlike "*localhost*") }

foreach ($appentry in $applist) {
    $principalId = $appentry.AppPrincipalId
    $principalName = $appentry.DisplayName
    
    $clientsecret = Get-MsolServicePrincipalCredential -AppPrincipalId $principalId -ReturnKeyValues $false |
                    ? { $_.Type -eq "Password" } |
                    % {
                        $principalName, $principalId;, ($enddate = $_.EndDate.ToString())
                    } |
                    select {$principalName}, {$principalId}, {$enddate}
     
    $clientsecret | Add-Member -MemberType NoteProperty -Name 'principalId' -Value $principalId
    $clientsecret | Add-Member -MemberType NoteProperty -Name 'principalName' -Value $principalName
    $clientsecrets+=$clientsecret

}

This will return around 140 rows or so, but if I would only catch the latest one of each uniqe (uniqe name + id) it should return 3.

First thing I did was trying to use the `Sort-Object -Property $enddate -Descending -Unique option but that won't do it, I tried any sort-object, select, with first, last etc that I can think of.

I never done something like this before, so I feel kinda lost here how to do the proper sorting.

Or as alternative, only get every uniqe one with an $enddate +1 day after today (yes, I tried using (Get-date).AddDays(1)) Anyone who can put me in right direction?

1 Answers

Obviously I did not think all the way.

    Where-Object {$enddate -gt (Get-Date $Datum -Format yyyy-MM-dd)} 
   | Sort-Object -Property $principalName -Unique

Fixes the problem, I am working on a computer where I don't have anything set to English, so with -format it fixed so it matches.

Related