4
votes

I have a simple script to show all certificates on a server, I would like to expand that script to then remove all expired certificates

I have tried several scripts from MS and 3rd parties to find a remove certs but have had no luck with them working properly

The first code I am using is:

Get-ChildItem Cert:\ -Recurse

This Powershell script shows all certificates on a server.

Example output is below for each certificate. I want to target the NotAfter field and have the script then remove the certificate if it's old than todays date

Subject: Issuer: Thumbprint: FriendlyName: NotBefore: NotAfter: Extensions

I would also like to do this for a list of servers, have the script run on each server in a text document, query all certificates, then remove the certs that are expired and move on to the next server.

I have seen some code targeting the date like the following:

ForEach-Object -begin { $now = get-date } -process { if ($PSItem.NotAfter -lt $now ) { $PSItem } } | Remove-Item

I would like the script to go out and query a servers certificates, then deletes out the expired certificates

1

1 Answers

6
votes

What you are after is this. This should work perfectly for you. You were close in your logic, just the execution seemed to be a bit off.

$ListOfServers = Get-Content "c:\temp\serv.txt"

Foreach($Server in $ListOfServers) {
    Invoke-Command -ComputerName $Server -ScriptBlock {
        # Get Certificate list and assign to a variable
        $Certs = Get-ChildItem "Cert:\LocalMachine\My" -Recurse

        # Loop through each object in $Certs
        Foreach($Cert in $Certs) {
            # If The objects property "NotAfter" is older than the current time, delete
            If($Cert.NotAfter -lt (Get-Date)) {
                $Cert | Remove-Item
            }
        }
    }
}

Edited based on comment to prevent accidental destruction of all certs.

To get a list of all cert storage locations.

(Get-ChildItem -Path "Cert:" -Recurse `
    | Where-Object {($_).GetType().Name -eq 'X509Store'}).Name