PowerShell Tip of the Week: Get certificate remotely

certificate

Get certificate details from remote machines. In this post I wanted to share simple script which check certificates expiration date.

Get certificate details

To get certificates details we can use Get-ChildItem command and provide cert path Cert:\LocalMachine\My. In this example I was looking for certificates which subject contains my computer name:

#Get computer name
[Environment]::GetEnvironmentVariable("computername")

#Get all certificates locally
Get-ChildItem Cert:\LocalMachine\My 

#Get certificates which name match your computername
Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.subject -match [Environment]::GetEnvironmentVariable("computername")}
certificate

As you can see above we get Thumbprint and Subject properties as default. In this case expiration date is what interesting me the most. We can display all other available properties by using Get-Member command:

(Get-ChildItem Cert:\LocalMachine\My) | Get-Member -MemberType Property
certificate

Property NotAfter is the one which tell us about expiration date. To get certificate details on remote machines we will use Invoke-Command:

  $Servers = "Server01",
             "Server02",
             "Server03",
             "Server04"

    $Results = @()
    $Results = Invoke-Command -cn $Servers {
	        $Certs = @{} | Select Certificate,Expired
	        $Cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.subject -match [Environment]::GetEnvironmentVariable("computername")}
	        If($Cert){
	            $Certs.Certificate = $Cert.subject
	            $Certs.Expired = $Cert.NotAfter
	        }
            Else{
	            $Certs.Certificate = " - "
	            $Certs.Expired = " - "
            }
	        $Certs
    } | Select-Object @{n='ServerName';e={$_.pscomputername}},Certificate,Expired

    #Display results in console
    $Results | Sort-Object Expired -Descending

    #Save results to CSV file
    $Results | Sort-Object Expired -Descending | Export-Csv -Path C:\users\$env:username\desktop\cert_results.csv -NoTypeInformation -Force

    #Open results in new window
    $Results | Sort-Object Expired -Descending | Out-GridView -Title "Final results"

Final results:

Results will be stored in $Results variable and you can display it in console, save into CSV file or open in new window using Out-GridView command:

certificate

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.