Get Expiring Certificate from Website

$minimumCertAgeDays = 60
$timeoutMilliseconds = 10000
$urls = @(
"https://meet.domain.local"
"https://anywebsite.domain.com"
)
#disabling the cert validation check. This is what makes this whole thing work with invalid certs…
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
foreach ($url in $urls)
{
$req = [Net.HttpWebRequest]::Create($url)
$req.Timeout = $timeoutMilliseconds
try {$req.GetResponse() |Out-Null} catch {}
function Convert-StringToDateTime
{
param
(
[Parameter(Mandatory = $true)]
[String] $DateTimeStr
)
# Change Date pattern to German
$DateFormatParts = (Get-Culture).DateTimeFormat.ShortDatePattern -split ‘/|-|\.’
$Month_Index = ($DateFormatParts | Select-String -Pattern ‘MM’).LineNumber – 1
$Day_Index = ($DateFormatParts | Select-String -Pattern ‘dd’).LineNumber – 1
$Year_Index = ($DateFormatParts | Select-String -Pattern ‘yyyy’).LineNumber – 1
$DateTimeParts = $DateTimeStr -split ‘/|-|\.| ‘
$DateTimeParts_LastIndex = $DateTimeParts.Count – 1
$DateTime = [DateTime] $($DateTimeParts[$Month_Index] + ‘/’ + $DateTimeParts[$Day_Index] + ‘/’ + $DateTimeParts[$Year_Index] + ‘ ‘ + $DateTimeParts[3..$DateTimeParts_LastIndex] -join ‘ ‘)
return $DateTime
}

$expiration = Convert-StringToDateTime $req.ServicePoint.Certificate.GetExpirationDateString()

[int]$certExpiresIn = ($expiration – $(get-date)).Days
$certName = $req.ServicePoint.Certificate.GetName()
$certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString()
$certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString()
$certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
$certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName()
if ($certExpiresIn -gt $minimumCertAgeDays)
{Write-Host ========================================================================`r`nCert for site $url expires in $certExpiresIn days [on $expiration] `r`n========================================================================`r`n -ForegroundColor Green}
else
# Following lines for testing to get Output on screen
#{Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] Threshold is $minimumCertAgeDays days. Check details:`n`nCert name: $certName`nCert public key: $certPublicKeyString`nCert serial number: $certSerialNumber`nCert thumbprint: $certThumbprint`nCert effective date: $certEffectiveDate`nCert issuer: $certIssuer -f Yellow `r`n}
#{Write-Host ========================================================================`r`nCert for site $url expires in $certExpiresIn days [on $expiration] Threshold is $minimumCertAgeDays days. Check details:`n========================================================================`nCert name: $certName`nCert Expires on:$expiration`nCert serial number: $certSerialNumber`nCert thumbprint: $certThumbprint`nCert effective date: $certEffectiveDate`nCert issuer: $certIssuer `r`n========================================================================`r`n -ForegroundColor Yellow} 
{$OutputToWrite = "========================================================================`r`nCert for site $url expires in $certExpiresIn days [on $expiration] Threshold is $minimumCertAgeDays days. Check details:`r`n========================================================================`r`nCert name: $certName`r`nCert Expires on:$expiration`r`nCert serial number: $certSerialNumber`r`nCert thumbprint: $certThumbprint`r`nCert effective date: $certEffectiveDate`r`nCert issuer: $certIssuer `r`n========================================================================`r`n"}
$OutputToWrite | Out-File C:\temp\ssl.txt -Encoding utf8

#Remove Variabel
rv req
rv expiration
rv certExpiresIn
}

 

Get Expiring Certifikate from Skype Environment

# ===================
# Global Variables
# ===================

# For Testing Purpose
# New-TimeSpan -Start (get-date) -End 21-06-2019

$Days = "75" # ATTENTION a variable does not funktion at AddDays with Powershell Version 3 in combination with Invoke. Version5 and up Works
$OutFile = "C:\Temp\Certlist.txt"

# ============================
# Create Array
# ============================
$Serverliste = @(
                    "Server01.domain.local"
                    "Server02.domain.local"
                    "Server03.domain.local"
                    "Server04.domain.local"
                  )

"Serverliste `r`n===========" | Out-File $OutFile
# ============================
# Reading out Certificates
# ============================
$Zertliste = (
Invoke-Command -ComputerName  $Serverliste -ScriptBlock  {Get-ChildItem Cert:\LocalMachine\My  | 
  Where {$_.NotAfter -lt  (Get-Date).AddDays(75)}} | Select-Object Issuer, NotAfter, SerialNumber, Subject, Use, DnsNameList | ForEach { #Added Days manuall because of Powershel Version 3

  [pscustomobject]@{
  ".===========" = "======================================="
  FQDN =  $_.Subject
  Issuer = $_.Issuer
  Use = $_.Use
  #Computername =  $_.PSComputername
  ExpiresOn =  $_.NotAfter
  DNSListNames = $_.DnsNameList 
  "============" = "======================================="
  }
  } |Sort-Object -Descending ) |Out-File $OutFile -Append


"Get-CScertificate`r`n=================" | Out-File $OutFile -Append

  Get-CsCertificate | Select-Object Issuer, NotAfter, SerialNumber, Subject, Use, AlternativeNames | 
  Where {$_.NotAfter -lt  (Get-Date).AddDays($Days)}| ForEach {

  [pscustomobject]@{
  ".===========" = "======================================="
  FQDN =  $_.Subject
  Issuer = $_.Issuer
  Use = $_.Use
  Computername =  $_.PSComputername
  ExpiresOn =  $_.NotAfter
  AlternativeNames = $_.AlternativeNames 
  "============" = "======================================="
  }
  } |Sort-Object -Descending | Out-File $OutFile -Append

  "List of Dns Names expiring in Lync Or Skype`r`n===================================================" | Out-File $OutFile -Append
  Get-CsCertificate | Where {$_.NotAfter -lt  (Get-Date).AddDays($Days)} | Select-Object -ExpandProperty AlternativeNames -Unique|
  Sort-Object -Descending | Out-File $OutFile -Append
  "===================================================" | Out-File $OutFile -Append


# ===================================================================
# Sending Mail if file is bigger then Empty kb.
# ===================================================================
$ToAddress = "admin@domain.local"
$FromAddres = "$env:computername.$env:userdnsdomain <$ToAddress>"
#$SmtpServer = "smtp.office365.com"
$SmtpServer = "mrelay.domain.local" # INFO: server that runs script must be allowed in FW, on mailrelay and in Virus Console outgoing connection to port 25 must be allowed!
#$SmtpPort = "587"
$Attachment = "$OutFile"
$Subject = "Certliste with Certificates that will Expire in $days from the Skype Environment"
#Body as HTML
$BodyHead = "This mail has been automaticly generated by the GetCSertificate script. <br> This Task runs following script C:\Temp\GetCSCertifikate.ps1. <br><br>See Attachment for expiring Certificates.<br>Please do not reply<br><br><br>"
$Body = "$BodyHead" + "$Zertliste"
#Body as Text
#$Body = "This is an automated mail used by a script. `r`n Please do not reply. `r`n `r See Attachment with log"

$mailparam = @{
    To = $ToAddress
    From = $FromAddres
    Subject = $Subject
    Body = $Body 
    Smtpserver = $SmtpServer
    #Port = $SmtpPort
    #Credential = $SmtpCred
    Attachment = $Attachment
    }

# =========================
# Check File for testing
# =========================
# Get-ChildItem -File $OutFile | select length

if( (get-item $OutFile).length -eq 434) {"File is blank"}
#If ((Get-Content $Attachment) -eq 1kb) {"File is blank"}
    Elseif  ((Get-Content $Attachment) -gt 434) {Send-MailMessage @mailparam -UseSsl -BodyAsHtml}

 

Get Expiring Certificate from Server Array

# The Following Website explaines very well how it works with Certificates.
# https://blogs.technet.microsoft.com/scotts-it-blog/2014/12/30/working-with-certificates-in-powershell/

# ================= Folowing things has to be done before you can query Remote Server==========================
# Enable-PSRemoting has to be run on every server.
# 
# On Server that are not reachable on the Standard Ports 5985 and 5986 you have to change the Listener to Http and Https.
# Set-Item WSMan:\localhost\Service\EnableCompatibilityHttpListener -Value true
# Set-Item WSMan:\localhost\Service\EnableCompatibilityHttpsListener -Value true
# The option -Port 443 oder 80 also has to be set.
#
# Check Listener: dir WSMan:\localhost\Service
# =============================================================================================================

# Example 1
#Get-ChildItem -Path Cert:\LocalMachine\My -Recurse | where { $_.notafter -le (get-date).AddDays(50) -AND $_.notafter -gt (get-date)} | select Friendlyname, subject, NotAfter

# Example 2
#Get-ChildItem –Recurse | where {$_.Notafter -le (get-date).AddDays(50) -AND $_.notafter -gt (get-date)}| select Friendlyname, subject, NotAfter | Format-Table NotAfter, FriendlyName, Subject
#Invoke-Command -Computername $Serverliste -ScriptBlock {Get-ChildItem Cert:\LocalMachine\My -Recurse | where {$_.Notafter -le (get-date).AddDays(750) -AND $_.notafter -gt (get-date)}| select subject, Friendlyname, NotAfter} | Format-Table subject, NotAfter, FriendlyName, DaysUntilExpired

Import-Module PKI
Set-Location Cert:\LocalMachine\My

# Treshold days that will expire
$treshold = 50

# ============================
# Create Array
# ============================
$Serverlist = @("server01.domain.local"
                "server02.domain.local"
                "server03.domain.local"
                "server04.domain.local"
                "server05.domain.local"
                  )

# ============================
# Das auslesen von Zertifikaten
# ============================
$Certlist = (
Invoke-Command -ComputerName  $Serverlist -ScriptBlock  {Get-ChildItem Cert:\LocalMachine\My  | 
  Where {$_.NotAfter -lt  (Get-Date).AddDays($treshold)}} | ForEach {

  [pscustomobject]@{
  FQDN =  $_.Subject
  #Computername =  $_.PSComputername
  ExpiresOn =  $_.NotAfter
  }
  } |Sort-Object -Descending |Out-File C:\Temp\Certlist.txt )


#===================================================================
$ToAddress = 'admin@domain.local'
$FromAddres = "$env:computername.$env:userdnsdomain <admin@domain.local>"
#$SmtpServer = 'smtp.office365.com'
$SmtpServer = "mrelay.domain.local" 
#$SmtpPort = '587'
$Attachment = "C:\Temp\Certlist.txt"
$Subject = "Certlist with Server that having a Certifcatite expring in $treshold days"
#Body as HTML
$BodyHead = 'This mail has been automaticly generated by the GetCertificate script. <br> This Task runs following script C:\Temp\GetCertifikate.ps1. <br><br>See Attachment for expiring Certificates.<br>Please do not reply<br><br><br>'
$Body = "$BodyHead" + "$Certlist"
#Body as Text
#$Body = "This is an automated mail used by a script. `r`n Please do not reply. `r`n `r See Attachment with log"

$mailparam = @{
    To = $ToAddress
    From = $FromAddres
    Subject = $Subject
    Body = $Body 
    Smtpserver = $SmtpServer
    #Port = $SmtpPort
    #Credential = $SmtpCred
    Attachment = $Attachment
    

    }

If ((Get-Content $Attachment) -eq $Null) {"File is blank"}
    Elseif  ((Get-Content $Attachment) -ne $Null) {Send-MailMessage @mailparam -UseSsl -BodyAsHtml}