2

We are in a disconnected domain and have just implemented updated root certificates via group policy. I have found now though, that there are a number of duplicated root certificates in the users store (and many more for mine as i've taken my laptop online once and a while).

I'm looking for a powershell script to go through the root certificate store and delete any duplicates in there.

I've got this so far:

$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("Root","LocalMachine")
$store.Open("ReadWrite")
$rootcerts = Get-Childitem 'cert:\LocalMachine\root' -Recurse
$ht = @{}
$rootcerts  | foreach {$ht["$_"] += 1}
$duplicates = $ht.keys | where {$ht["$_"] -gt 1}

but then how to delete the duplicates has lost me.

1
  • Have you checked that you actually find any duplicates? Commented Nov 29, 2015 at 23:02

1 Answer 1

0

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]"${Value.GetDateTimeString()}" -Descending |
            Select-Object -ExpandProperty Value -Skip 1 |
            ForEach-Object {
                if (Test-Path $_.PSPath) {
                    Remove-Item -Path $_.PSPath -DeleteKey
                }
            }
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .