Instead of updating a count based off the cert object you need to save off more information about the certificate during your iteration. I chose to create an additional map of thumbprints as keys and the cert objects as values. So the lookup is first by subject, and then by thumbprint.
I then remove the oldest certs and leave the newest.
$ht = @{} Get-ChildItem -Recurse Cert:\LocalMachine\My | Where-Object { $_.Issuer -like "*MyIssuer*" } | ForEach-Object { $subject = $_.Subject if (!$ht.ContainsKey($subject)) { $ht[$subject] = @{} } $ht[$subject]["$($_.Thumbprint)"] = $_ } $ht.Keys | ForEach-Object { $dupes = ($ht[$_] | Where-Object { $_.Count -gt 1 }) if ($dupes) { $dupes.GetEnumerator() | Sort-Object [DateTime]"$" -Descending | Select-Object -ExpandProperty Value -Skip 1 | ForEach-Object { if (Test-Path $_.PSPath) { Remove-Item -Path $_.PSPath -DeleteKey } } } }