Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a certificate from the local machine certificate store in powershell?

Tags:

powershell

I am trying to check for, and then remove a certificate if it exists in a user's local machine store. I've tried this:

$certCN = 'test.domain.com'
Set-Location Cert:\LocalMachine\My
$oldCert = Get-ChildItem -Recurse | 
Where-Object { $_.subject -like "CN=$oldCert*" }
Remove-Item Cert:\LocalMachine\My\$oldCert -Force

But it is not removing the cert from the store or giving any errors (yes I am running this elevated).

I checked my $oldCert variable to see if it is populated and it is:

PS Cert:\LocalMachine\My> $oldcert
PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\My

Thumbprint                                Subject                                                                                                                                                                       
----------                                -------                                                                                                                                                                       
276B7B87740D5E9595A258060F5CD9CC4190E9E1  CN=test.domain.com, <truncated>

Does anyone know how to accomplish this? I really appreciate it.

like image 685
Dominic Brunetti Avatar asked Nov 06 '25 01:11

Dominic Brunetti


1 Answers

The problem you're encountering is the automatic string conversion of the X509Certificate2 object from the Cert:\ drive. When you're appending it to your path as -Path some\path\$myobj, it's implicitly calling ToString on the object. You can observe this by doing "some\path\$myobj" at the console without any other code or by simply calling $myobj.ToString().

Because Remove-Item takes pipeline input by property name, it will automatically pull the path off your object when you pass it over the pipeline, so you can remediate your problem simply as such:

$oldCert | Remove-Item

or

Remove-Item -LiteralPath $oldCert.PSPath
like image 155
Maximilian Burszley Avatar answered Nov 07 '25 15:11

Maximilian Burszley