对于Server 2008 系列证书的删除和添加需要借助.net 类进行

移除证书

$thumbprint = gci Cert:\LocalMachine\my |?{$_.Subject -eq "CN=server01.contoso.com"}
$store = New-Object System.Security.Cryptography.x509Certificates.x509Store("My","LocalMachine")
$store.Open("ReadWrite")
$removecert = $store.Certificates |?{$_.Thumbprint -eq $thumbprint}
$store.Remove($removecert)
$store.Close()


添加证书

function Import-PfxCertificate { 
param([String]$certPath,[String]$certRootStore = "localmachine",[String]$certStore = "My",$pfxPass = $null)
$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
if ($pfxPass -eq $null)
{
$pfxPass = ConvertTo-SecureString "123" -AsPlainText -Force
}
$pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet")
$store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
}
Import-PfxCertificate "C:\certs\$fqdn.pfx" "LocalMachine" "My"


对于Server 2012 及以上可以通过Powershell 3.0 内核自带的命令


添加证书

$certpath = "C:\server01.pfx"
Import-PfxCertificate -FilePath $certpath -CertStoreLocation Cert:\LocalMachine\My -Password (ConvertTo-SecureString '123' -AsPlainText -Force)


移除证书

$expirecert = Get-ChildItem Cert:\LocalMachine\My |?{$_.Subject -eq 'CN=server01'}
$thumbprint = $expirecert.Thumbprint
Remove-Item "Cert:\LocalMachine\my\$thumbprint" -Confirm:$false -Force # remove certificate from cert store