Sql-server – How to remove an installed AE certificate from server using PowerShell Scripts

always-encryptedpowershellsql-server-2016

I have created the encryption certificate using below PowerShell script in dev. environment. Now, I need to create deployment document to configure the encryption on staging environment.

$cert = New-SelfSignedCertificate -Subject "AlwaysEncryptedCert" -CertStoreLocation Cert:LocalMachine\My -KeyExportPolicy Exportable -Type DocumentEncryptionCert -KeyUsage KeyEncipherment -KeySpec KeyExchange -KeyLength 2048

I need to keep the rollback PowerShell scripts to remove the certificate from local machine. What is the correct way of removing the certificate using PowerShell scripts? Can anyone guide me on this?

Best Answer

It is just Remove-Item to remove the certificate, and then include -DeleteKey to also drop the private key.

Based on your command it should be something like this as you have to pass in the thumbprint of the certificate to the remove command, so we need to look it up first:

Get-ChildItem -Path Cert:\LoaclMachine\My -Recurse -DocumentEncryptionCert | 
    Where-Object Subject -eq 'AlwaysEncryptedCert' | Remove-Item -WhatIf