Functions/CertificateManagement/Uninstall-FpsCertificate.ps1

<#
.SYNOPSIS
    Uninstalls the certificate from the Windows Certificate Store.
.DESCRIPTION
    This cmdlet won't uninstall the certificate if the thumbprint still is configured on a Business Central ServerInstance or IIS Website.
    Use the Force switch to uninstall the certificate anyway. Recommended practice is to use Update-FpsCertificate to replace the (expired) certificate with a new certificate.
.EXAMPLE
    Uninstall-FpsCertificate -Thumbprint '008CEE1FEA5RANDOM2AF4F603EBPRINTBB0341D1'
.EXAMPLE
    Uninstall-FpsCertificate -ThumbPrint '008CEE1FEA5RANDOM2AF4F603EBPRINTBB0341D1' -CertificatePath 'cert:\CurrentUser\My'
#>

function Uninstall-FpsCertificate{
    [CmdletBinding()] 
    param(
        # The Certificate thumbprint
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [ValidatePattern('^[a-zA-Z\d]+$')]
        [string] $Thumbprint,

        # The certificate provider path where to scan for certificates. Path should start with 'Cert:'. E.g. 'cert:\LocalMachine\WebHosting'.
        [Parameter(ValueFromPipelineByPropertyName=$true)]
        [string] $CertStorePath = 'cert:\LocalMachine\My',

        # When force is enabled the certificate will be uninstalled even though it is still used on Business Central ServerInstances or IIS Web Sites.
        [Parameter(ValueFromPipelineByPropertyName=$true)]
        [switch] $Force
    )

    $cert = Get-FpsCertificate -ThumbPrint $Thumbprint -CertStorePath $CertStorePath -IncludePublicCertificates -ReturnCertObject
    
    'Validating if the certificate is still configured on a Business Central ServerInstance or IIS Website...' | Write-Host

    $return = $false
    if(-not [string]::IsNullOrEmpty($cert.UsedOnBcServerInstances)){
        Write-Warning ('Certificate ''{0}'' with thumbprint {1} is still used on Business Central ServerInstance(s) {2}. Use force to uninstall the certificate.' -f
            $cert.FriendlyName, $cert.Thumbprint, ($cert.UsedOnBcServerInstances -join ', '))
        if(!$force){$return = $true}
    }
    if(-not [string]::IsNullOrEmpty($cert.UsedOnIISWebSites)){
        Write-Warning ('Certificate ''{0}'' with thumbprint {1} is still used on Web Site(s) {2}. Use force to uninstall the certificate.' -f
            $cert.FriendlyName, $cert.Thumbprint, ($cert.UsedOnIISWebSites -join ', '))
        if(!$force){$return = $true}
    }
    if($return){return}

    'Removing certificate ''{0}'' with thumbprint {1}...' -f $cert.FriendlyName, $cert.Thumbprint | Write-Host
    Get-FpsCertificate -ThumbPrint $Thumbprint -CertStorePath $CertStorePath -IncludePublicCertificates -ReturnCertObject | Remove-Item
    'Certificate ''{0}'' with thumbprint {1} has been removed' -f $cert.FriendlyName, $cert.Thumbprint | Write-Host
}
Export-ModuleMember -Function Uninstall-FpsCertificate