SOLVED

Monitor  SSL Certificates that will be expired soon and also provide an email notification

Copper Contributor

Hello,

I have the following code in order to monitor  SSL Certificates that will be expired soon and also provide an email notification at the end.

To be clear i have found that code from this link https://www.msnoob.com/powershell-script-get-certificate-that-will-be-expired-soon.html 

 

 

Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction silentlyContinue

##### Email Configuration Section ##### 

$SMTPName = ""
$EmailMessage = new-object Net.Mail.MailMessage
$SMTPServer = new-object Net.Mail.SmtpClient($SMTPName)
$EmailMessage.From = "alexandros.ananikidis@sag-ag.ch"
$EmailMessage.To.Add("alexandros.ananikidis@sag-ag.ch")

##### Enter Serverr List ##### 
$servername="https://www.google.com"

##### Enter the remaining date before certificate is expired ######
$daysremain=30
 
 
$certlist=Invoke-Command -ComputerName $servername {Get-ChildItem Cert:\LocalMachine\My -Recurse |
    Where-Object {$_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2] -and $_.NotAfter -gt (Get-Date) -and $_.NotAfter -lt (Get-Date).AddDays($daysremain)}
    }


if ($certlist){
    # Begin creation of the HTML for the email
    $body = "<head>"
    $body = $body + "<style>"
    $body = $body + "BODY{background-color:white;}" 
    $body = $body + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}" 
    $body = $body + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:grey}" 
    $body = $body + "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color:white}" 
    $body = $body + "td.green{background-color: green; color: black;}"
    $body = $body + "td.gray{background-color: gray; color: black;}"
    $body = $body + "td.silver{background-color: silver; color: black;}"
    $body = $body + "td.fsdata{background-color: #87AFC7; color: black;}"
    $body = $body + "td.red{background-color: red; color: black;}"
    $body = $body + "H4{background-color: Gold; color: black;}"
    $body = $body + "H5{color: gray;}"
    $body = $body + "</style>"
    $body = $body + "</head>"
    $body = $body + "<body>"
    $body = $body + "<font size=" + '"2"' + " face=" + '"arial black"' + ">"
    $body = $body + "<H3 align=" + '"center"' + ">Warning, SSL Certificate(s) in server $servername needs your attention</H3>"
    $body = $body + "</font>"

    foreach ($certificate in $certlist) {
        $body = $body + "<font align="+ '"left"' +">Certificate Issued To = " +  $certificate.Issuer + "</font><br />"
        $body = $body + "<font align="+ '"left"' +">Expired Date = " +  $certificate.NotAfter + "</font><br /><br />"
    }

    $body = $body + "</body>"


    ##### Send The email with result #####
    $EmailMessage.Subject = "[ATTENTION] There is SSL Certificate(s) that need your attention"
    $EmailMessage.Body = $body
    $EmailMessage.IsBodyHTML = $true 
    $SMTPServer.Send($EmailMessage)
}

 

 

Nevertheless, when i try to run it i get the following error:

 

 

Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings.
At line:18 char:11
+ $certlist=Invoke-Command -ComputerName $servername {Get-ChildItem Cer ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (System.String[]:String[]) [Invoke-Command], ArgumentException
    + FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.InvokeCommandCommand

 

 

I also tried with the  -ConnectionUri parameter instead of -ComputerName  but still it fails.

I am really new with all that PowerShell commands so can maybe someone help me on how to change my code?

 

Thank you a lot

Alexandros

7 Replies

@Alexandros8888 

HI, 

did you try to set the $Servername variable with the actual server name?

Hello @farismalaeb,

Thank you for your reply. I also tried yes.

I tried like that:

 

Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction silentlyContinue

##### Email Configuration Section ##### 

$SMTPName = ""
$EmailMessage = new-object Net.Mail.MailMessage
$SMTPServer = new-object Net.Mail.SmtpClient($SMTPName)
$EmailMessage.From = "alexandros.ananikidis@sag-ag.ch"
$EmailMessage.To.Add("alexandros.ananikidis@sag-ag.ch")

##### Enter Serverr List ##### 


##### Enter the remaining date before certificate is expired ######
$daysremain=30
 
 
$certlist=Invoke-Command -ComputerName https://www.google.com {Get-ChildItem Cert:\LocalMachine\My -Recurse |
    Where-Object {$_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2] -and $_.NotAfter -gt (Get-Date) -and $_.NotAfter -lt (Get-Date).AddDays($daysremain)}
    }


if ($certlist){
    # Begin creation of the HTML for the email
    $body = "<head>"
    $body = $body + "<style>"
    $body = $body + "BODY{background-color:white;}" 
    $body = $body + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}" 
    $body = $body + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:grey}" 
    $body = $body + "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color:white}" 
    $body = $body + "td.green{background-color: green; color: black;}"
    $body = $body + "td.gray{background-color: gray; color: black;}"
    $body = $body + "td.silver{background-color: silver; color: black;}"
    $body = $body + "td.fsdata{background-color: #87AFC7; color: black;}"
    $body = $body + "td.red{background-color: red; color: black;}"
    $body = $body + "H4{background-color: Gold; color: black;}"
    $body = $body + "H5{color: gray;}"
    $body = $body + "</style>"
    $body = $body + "</head>"
    $body = $body + "<body>"
    $body = $body + "<font size=" + '"2"' + " face=" + '"arial black"' + ">"
    $body = $body + "<H3 align=" + '"center"' + ">Warning, SSL Certificate(s) in server $servername needs your attention</H3>"
    $body = $body + "</font>"

    foreach ($certificate in $certlist) {
        $body = $body + "<font align="+ '"left"' +">Certificate Issued To = " +  $certificate.Issuer + "</font><br />"
        $body = $body + "<font align="+ '"left"' +">Expired Date = " +  $certificate.NotAfter + "</font><br /><br />"
    }

    $body = $body + "</body>"


    ##### Send The email with result #####
    $EmailMessage.Subject = "[ATTENTION] There is SSL Certificate(s) that need your attention"
    $EmailMessage.Body = $body
    $EmailMessage.IsBodyHTML = $true 
    $SMTPServer.Send($EmailMessage)
}

  But i get that error:

 

Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or 
pass URI objects instead of strings.
At line:18 char:11
+ $certlist=Invoke-Command -ComputerName https://www.google.com {Get-Ch ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (System.String[]:String[]) [Invoke-Command], ArgumentException
    + FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.InvokeCommandCommand

Best regards,

Alexandros

@Alexandros8888 

try this small change

 

$certlist=Invoke-Command -ComputerName $servername -scriptblock {Get-ChildItem Cert:\LocalMachine\My -Recurse | Where-Object {$_.NotAfter -lt (Get-Date).AddDays($daysremain)}}

 

and make sure that the server is the FQDN of the server or NETBIOS name such as "mylocalserver"

Hello @farismalaeb,

 

Thank you for your  valuable and fast support.

 

I tried to create something even simpler that the code that i have found that works for me.

 

So i ended up with the following more simple code:

 

$Urls = @()
$Urls = "https://google.com",
"https://prod-caesar-service-app.apps.sag.services/"


$Result = @()


$MinimumCertAgeDays = 5000
$ErrorActionPreference= 'silentlycontinue'

Foreach ($url in $Urls)
{
[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

$req = [Net.HttpWebRequest]::Create($url)
$req.GetResponse() | Out-Null
#$req.ServicePoint.Certificate.GetExpirationDateString()

$ExpirationDate = $req.ServicePoint.Certificate.GetExpirationDateString()
$ExpDateToDT = [Datetime]::ParseExact($ExpirationDate, "dd/MM/yyyy hh:mm:ss", $null)
$DayCount = ( $( $ExpDateToDT ) - $( Get-Date ) ).Days

If ( $DayCount -le $MinimumCertAgeDays )
 {  
 
  
 $Result += "
   ---Certificate for Host: $url  Expires on ----->  $ExpirationDate
   ---Certificate for Host: $url  Expires in ----->  $DayCount DAYS" 
       

 }

}


Write-Output $Result


# Sender and Recipient Info
$MailFrom = "alexandros.ananikidis@sag-ag.ch"
$MailTo = "alexandros.ananikidis@sag-ag.ch"

# Sender Credentials
$Username = "alexandros.ananikidis@sag-ag.ch"
$Password = "Mypass"

# Server Info
$SmtpServer = "smtp-mail.outlook.com"
$SmtpPort = "587"

# Message stuff
$MessageSubject = "Live your best life now" 
$Message = New-Object System.Net.Mail.MailMessage $MailFrom,$MailTo
$Message.IsBodyHTML = $true
$Message.Subject = $MessageSubject
$Message.Body = $Result 

# Construct the SMTP client object, credentials, and send
$Smtp = New-Object Net.Mail.SmtpClient($SmtpServer,$SmtpPort)
$Smtp.EnableSsl = $true
$Smtp.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
$Smtp.Send($Message)

 It works fine.

 

The only issue that i need support now is how to make my email response to include some change of lines as the attached image show. Because it is really hard to read. 

 

Can you maybe help on that one?

 

Thank you a lot in advance,

Alexandros 

best response confirmed by Alexandros8888 (Copper Contributor)
Solution

@Alexandros8888 

I hope I understand the last response correct but try to do this change in the $Result Variable

 

$Result += "
<br>Certificate for Host: $url Expires on -----> $ExpirationDate
<br>Certificate for Host: $url Expires in -----> $DayCount DAYS"

 

The output will be much better and each certificate will be in a separate line

 

@farismalaeb  Thank you very much for your help :)

 

Best regards,

Alexandros

Hi, can you please help in this context ? I am trying the original script but it is not giving any output .
1 best response

Accepted Solutions
best response confirmed by Alexandros8888 (Copper Contributor)
Solution

@Alexandros8888 

I hope I understand the last response correct but try to do this change in the $Result Variable

 

$Result += "
<br>Certificate for Host: $url Expires on -----> $ExpirationDate
<br>Certificate for Host: $url Expires in -----> $DayCount DAYS"

 

The output will be much better and each certificate will be in a separate line

 

View solution in original post