function Get-ExpiringCertificates { <# .SYNOPSIS Gets certificates that will expire soon. .DESCRIPTION Takes a list of machines and connects to their certificate stores, compares the expiration date to a configureable threshold date. If the expiration date is less than the threshold date the certificate is returned in a list. .PARAMETER ComputerName [string[]]One or more computers on which to get expired certificates from. .PARAMETER ExpirationThreshold [int] An amount of days you wish to set the threshold. Note* Can be negative. Defaults to 30 .EXAMPLE Get-ExpiringCertificates "Server1","Server2" Will connect to these servers in parallel, and retrieve certificates that are due to expire within 30 days or less from now. .EXAMPLE Get-ExpiringCertificates "Server1","Server2" -Threshold 90 Will connect to these servers in parallel, and retrieve certificates that are due to expire within 90 days or less from now. #> [CmdletBinding()] param( [Parameter(Mandatory=$true)] [Alias("Servers","Machines")] [string[]]$ComputerName, [Parameter(Mandatory=$false)] [int]$ExpirationThreshold = 30 ) begin{ #Ensure there are machines to connect to $sessions = New-PSSession $ComputerName -ErrorAction SilentlyContinue; $Unreachable = $ComputerName | Where-Object {$sessions.ComputerName -notcontains $_} if($Unreachable){Write-Host "Could not connect to $Unreachable";} if(!$sessions){throw "Could not connect to any machines";} } process{ $ScriptBlock = { param($ExpirationThreshold); $personalStore = [System.Security.Cryptography.X509Certificates.StoreName]::My; $machineStore = [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine; $certificates = [Alkami.Ops.Common.Cryptography.CertificateHelper]::GetAllCertificates($personalStore, $machineStore, $env:COMPUTERNAME); $expirationThresholdDate = (Get-Date).AddDays($ExpirationThreshold); #Filter certificates by threshold date $expiredCertificates = $certificates | Where-Object {$_.notAfter -lt $expirationThresholdDate} | ` Select-Object @{N="Machine";E={$env:COMPUTERNAME}},@{N="ExpirationDate";E={$_.NotAfter}},` @{N="DaysRemaining";E={(New-TimeSpan -start (get-date) -end $_.notAfter | Select-Object -ExpandProperty days)}},Thumbprint,FriendlyName,Subject; if($expiredCertificates){Write-Output $expiredCertificates;} } #Connect to machines and execute $expiredCertificates = Invoke-Command -Session $sessions -ScriptBlock $ScriptBlock -ArgumentList $ExpirationThreshold; Remove-PSSession $sessions; return $expiredCertificates; } }