Profile Power: Tidy Up My Personal Certificate Store

I've decided to do a few posts on the contents of my PowerShell profile.

A profile is a script that runs when your PowerShell console starts. There is a profile for the ISE and the standard console. You can find the script location by looking at the $profile variable of the current host.


What's in a profile?

I have loads of functions and code snippets and customisations in my profile. Some of them change the console look and feel, some set default parameter values, some load useful functions and others perform housekeeping.

Here's a housekeeping snippet. It deletes old or archived certificates from my personal certificate store.


$store = New-Object  System.Security.Cryptography.X509Certificates.X509Store "My","CurrentUser"

$MaxAllowedIncludeArchive = ([System.Security.Cryptography.X509Certificates.openflags]::MaxAllowed –bor [System.Security.Cryptography.X509Certificates.openflags]::IncludeArchived)


[System.Security.Cryptography.X509Certificates.X509Certificate2Collection]$certificates = $store.certificates

foreach ($cert in $certificates) {

    if (($cert.notAfter -lt (Get-Date)) -or ($cert.Archived)) {

        Write-Output "Name: $($cert.IssuerName.Name)"
        Write-Output "NotAfter: $($cert.NotAfter)"
        Write-Output "Archived: $($cert.Archived)"
        Write-Output "Removed: True"


        Write-Output " "





What's going on?

Create an object for the current user's personal certificate store. Set a couple of opening flags. Open the store. Obtain the certificates from the store.

Loop through each certificate and  if it is archived or no longer valid (notAfter) remove it.



Comments (0)

Skip to main content