How to remove a certificate from a certificate store programmatically (PowerShell)

Hi all,

The following sample will remove a certificate from MY certificate store of the local machine after locating it by serial number:

# Pass Serial Number of the cert you want to remove param ($serialNumber = $(throw "Please pass a certificate's serial number to the script")) # Access MY store of Local Machine profile $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine") $store.Open("ReadWrite") # Find the cert we want to delete $cert = $store.Certificates.Find("FindBySerialNumber",$serialNumber,$FALSE)[0] if ($cert -ne $null) { # Found the cert. Delete it (need admin permissions to do this) $store.Remove($cert) Write-Host "Certificate with Serial Number" $serialNumber "has been deleted" } else { # Didn't find the cert. Exit Write-Host "Certificate with Serial Number" $serialNumber "could not be found" } # We are done $store.Close()

 

Note: this sample attacks the local machine profile, so by default you will need admin permissions to remove certs from its MY store.

I hope this helps.

Regards,

 

Alex (Alejandro Campos Magencio)