Powershell: Cleanup Certificates issued by Template on Workplace/Server
One of my customer deployed a Certification Authority and distributed wrong certificates (lifetime and purpose was wrong).
Because the customer does not want to revoke all certificates he created a new template and supersede the old templates. Nevertheless not all certificates have been replaced on the workplace/server but new certificates have been issued. Therefore the customer asked if it is possible to cleanup all certificates based on the wrong template.
I wrote a small Powershell script to do the work and created a GPO which creates a scheduled task with system privileges and linked this GPO to the workplace and server. This scheduled task executes and checks all certificates in the my store of the computer.
$unwantedcerts = "*Workstation_Authentication(*","*Client*","*Client_WLAN*" $certs = Get-ChildItem cert:/LocalMachine/My $LogFile = "\\company.loc\reportcert\cert_$env:Computername.txt" function write-log ($Inhalt) { $FileExists = test-path $LogFile $DateNow = Get-Date -Format "dd.MM.yyyy HH:mm" # Ermittelt das aktuelle Datum mit diesem Syntax 01.10.2013 10:00 $FileInp = $DateNow + ' | ' + $Inhalt # Setzt die Zeile für unser Logfile zusammen If ($FileExists -eq $True){ # Wenn dir Datei existiert reinschreiben Add-Content $LogFile -value $FileInp # Zeile hinten an die vorhanden Einträge anhängen write-Host $Inhalt } else { New-Item $Logfile -type file # Wenn dir Datei nicht existiert anlegen Add-Content $LogFile -value $FileInp # und reinschreiben write-host $Inhalt } } #Prüfen ob OS Deutsch if (([CultureInfo]::InstalledUICulture).Name -notlike "de-DE") { write-host "OS is not German!!!" -ForegroundColor Red exit } #OID Friendly Name hinzufügen foreach ($cert in $certs) { foreach ($FriendlyName in $cert.Extensions.OID.FriendlyName) { $cert | add-member -MemberType NoteProperty -Name $FriendlyName -Value ($cert.Extensions | where {$_.OID.FriendlyName -eq $FriendlyName}).Format(0) } } #Zertifikate prüfen ob über Template bereitgestellt, wenn ja prüfen ob zu löschendes Template dabei ist und Zertifikat löschen foreach ($cert in $certs) { if (!($cert.Zertifikatvorlageninformationen)) { Write-Log "'$($cert.FriendlyName)' has not Issued by Template - ignore" continue } else { $unwantedcerts | foreach { if ($cert.Zertifikatvorlageninformationen -like $_) { #delete Remove-Item $cert.PSPath -Force -Confirm:false Write-Log "'$($cert.Subject)'delete the unwanted cert" continue }} Write-Log "'$($cert.Subject)' does not match the unwanted cert - ignore" } }