Powershell. Loop through certificate store and remove cert based on thumbprint

Viewed 909

I have a simple powershell script that runs via a GPO startup script. As you can see, it takes a thumbprint an loops through the cert store and removes it if it finds it.

#thumbprint of certificate to remove
$thumb = "abcdef444444857694df5e45b68851868"

#loop through all the certs stores looking for $thumb and remove if found
get-childitem Cert:/ -recurse | where-object {$_.thumbprint -contains "$thumb"} | remove-item

When I run the above two lines from an elevated powershell prompt it works!

If I reboot my machine and let the GPO do it's thing OR if I run from an elevated powershell prompt the below:

powershell.exe -Noninteractive -ExecutionPolicy Bypass -Noprofile -file "\\mydomain.corp\SysVol\mydomain.corp\Policies\{7086C68E-D509-9169-A02B-56579826C234}\Machine\Scripts\Startup\removecerts.ps1"

Then I get the following:

remove-item : The operation is on user root store and UI is not allowed.

Any help would be appreciated.

2 Answers

I suspect it's prompting for confirmation, which it can't when running headless.

Adding the -Force parameter should override the confirmation prompt:

... | Remove-Item -Force

Alternatively, set the $ConfirmPreference variable to None before attempting to remove the certificates to avoid the prompt:

$ConfirmPreference = 'None'
<# rest of script goes here #>

script now looks like this:

$ConfirmPreference = 'None'

#thumbprint of certificate to remove
$thumb = "abcdef444444857694df5e45b68851868"

#loop through all the certs stores looking for $thumb and remove if found
get-childitem Cert:/ -recurse | where-object {$_.thumbprint -contains "$thumb"} | remove-item -Force

And my error:

remove-item : The operation is on user root store and UI is not allowed.
At \\mydomain.corp\SysVol\mydomain.corp\Policies\{7086C68E-D509-9169-A02B-56579826C234}\Machine\Scripts\Startup\removecerts.ps1:16 char:88
+ ...  {$_.thumbprint -match "$thumb"} | remove-item -Force
+                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-Item], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.RemoveItemCommand
    ```
Related