Wednesday, September 20, 2017

Powershell : Certutil Find Expired Certs on CA server

Wrote this to get certificate expiration information for certificates that expired 5 days ago to ones that expire in 90 days. Wrap this around an invoke-command for remote query.
$Before = (get-date).adddays(90).ToString("MM/dd/yyyy")
$After = (get-date).AddDays(-5).ToString("MM/dd/yyyy")
<#

https://blogs.technet.microsoft.com/poshchap/2016/01/01/powershell-and-certutil-exe/
We create a date range with
$Before, i.e. certificates expiring before this date, and
$After, i.e. certificates expiring after this date. These values are converted into something that certutil can understand - $Restrict. This is then used with the certutil -restrict parameter.
#>
$Restrict = "NotAfter<=$Before,NotAfter>=$After"
$Report = @()
$cmd = & certutil.exe -view -restrict $Restrict -out "RequesterName,CommonName,Certificate Expiration Date","Certificate Template"

$SplitLines = $cmd.Split("`n`r")

$Index = 0
foreach ($line in $SplitLines){

    if ($line -like "Row*" ){
        $Details = New-Object PSObject 
        $Details | Add-Member noteProperty "RequesterName" $SplitLines[$index+1].split(":")[1].Replace("`"","").Replace(" ","")
        $Details | Add-Member noteProperty "CommonName" $SplitLines[$index+2].split(":")[1].Replace("`"","").Replace(" ","")
        $Details | Add-Member noteProperty "Certificate Expiration Date" $SplitLines[$index+3].split(':')[1].split(" ")[1].Replace(" ","")

        
        if ($SplitLines[$index+4].split(":")[1].Replace("`"","") -notlike "*1.*") {
            $TemplateName = $SplitLines[$index+4].split(":")[1].Replace("`"","").Replace(" ","")
        }
        Else {
        write-host "hit"
        $templatename = $SplitLines[$index+4].split(":")[1].Replace("`"","").split(" ")[2].Replace(" ","")
        }

        $Details | Add-Member noteProperty "Certificate Template" $TemplateName
        
        
        
        $report += $Details 
    
    }

    $Index++
}
$report

No comments:

Post a Comment