Search code examples
powershellssl-certificateiis-8iis-10

How can I use Powershell to find when an SSL certificate expires for ONLY IIS for a list of servers from OU?


I have this section of code that if I can merely get the script to ONLY reply with Subject that exists (which indicates the IIS cert), then I can be done... (I have the OU enumeration, and the Invoke section down, and the email of the file for scheduling in a task): [NOTE: I have the expiration set to 500 days so I can then use the script later to merely find specific expiration times] [NOTE2: $day is set in my $profile to '$day = Get-Date -Format yyyyMMdd']

    $serverlist = $serverListpath.Name
    foreach($server in $serverlist){
        if($server -like '#*')
        {
            continue
        }
    
    $threshold = 500   #Number of days to look for expiring certificates
    $deadline = (Get-Date).AddDays($threshold)   #Set deadline date
    $p = ($c++/$server.count) * 100
     Write-Progress -Activity "Checking $._" -Status "$p % completed" -PercentComplete $p;
     if(Test-Connection -ComputerName $server -Count 2 -Quiet){
     #$server = "KnownIISServerHostname" #<-- to test with a hostname
    Invoke-Command -Verbose -ComputerName $server { Dir Cert:\LocalMachine\My } |`
foreach {
    If ($_.NotAfter -le $deadline) { 
$_ | Select *| select PSComputerName, Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}} }
    }|`
select PSComputerName,Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}} |`
    export-csv -Force -Append -Encoding ASCII -NoTypeInformation .\output\$day-ExpiringIISSSLCerts.csv
    }
    }

So where do I tweak this to get the reply to ONLY have existing "Subject" fields; Not to get the null subject field replies (which are RDP certificates)


Solution

  • #checkCertExpDate-manual.ps1
    $day = Get-Date -Format yyyyMMdd
    $threshold = 5000   #Number of days to look for expiring certificates
    $deadline = (Get-Date).AddDays($threshold)   #Set deadline date
    Dir Cert:\LocalMachine\My | foreach {
    If ($_.NotAfter -le $deadline) { $_ | Select Issuer, Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}} }
    }
    

    Then you just grep for the name:

    .\checkCertExpDate-manual.ps1|Select-String -pattern "companyname"
    

    Now, I can set the '$threshold' to whatever I want...

    I invoke this remotely, after I copied to every server, and wrote the output to a log I then email to myself automatically every week from a scheduled task.