Retired Microsoft Blog disclaimer

This directory is a mirror of retired "Decrypt My World" MSDN blog and is provided as is. All posting authorship and copyrights belong to respective authors.
Original URL: https://blogs.msdn.microsoft.com/alejacma/2012/04/27/how-to-remove-a-certificate-from-a-certificate-store-programmatically-powershell/
Post name: How to remove a certificate from a certificate store programmatically (PowerShell)
Original author: Alejandro Campos Magencio
Posting date: 2012-04-27T05:37:23+00:00


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)


Share this article:

Comments:

Comments are closed.