<#
.SYNOPSIS

.NOTES
    Version        : 1.0
    Author         : Hubert CORNET
    Creation Date  : 16/11/2022
    Purpose/Change :

.LINK
    https://www.tips-of-mine.fr

.EXEMPLE

.DESCRIPTION

.PARAMETER <Parameter_Name>

.INPUTS

.OUTPUTS

#>

#---------------------------------------------------------[Initialisations]--------------------------------------------------------

# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"

# Bibliothèques de fonctions requises

#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"

#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "<script_name>.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName

$Folder = "C:\TradeXpress5\users\ediprod\ssl\certs"
$ListCert = dir $Folder -Include *.cer, *.crt, *.cert -Recurse
$dtCurrent = Get-Date

$bReturnOK           = $TRUE
$bReturnCritical     = $FALSE
$bReturnWarning      = $FALSE
$returnStateOK       = 0
$returnStateWarning  = 1
$returnStateCritical = 2
$returnStateUnknown  = 3

$nWarning    = 60
$nCritical   = 30
$strCritical = ""
$strWarning  = ""
$DataTexte   = ""

#-----------------------------------------------------------[Functions]------------------------------------------------------------

#------------------------------------------------------------[Script]--------------------------------------------------------------

cls

Foreach ($Certificate in $ListCert) {
    $objCertificate = New-Object Security.Cryptography.X509Certificates.X509Certificate2 $Certificate.FullName
    $dtRemain =  $objCertificate.NotAfter - $dtCurrent
    $nRemainDays = $dtRemain.Days

    $DataTexte += "'"+$Certificate.name+"'="+$nRemainDays+" "

    If ($nRemainDays -lt 0) {
    	$strCritical = $strCritical + "EXPIRED " + $objCertificate.SubjectName.Name.ToString() + " expired " + $objCertificate.NotAfter.ToString() + "`n"
    	$bReturnCritical = $TRUE
    }
    Elseif ( $nRemainDays -lt $nCritical) {
        $strCritical = $strCritical +  "Critical " + $objCertificate.SubjectName.Name.ToString() + " expires " + $objCertificate.NotAfter.ToString() + "`n"
	    $bReturnCritical = $TRUE
    }
    Elseif ( $nRemainDays -lt $nWarning) {
        $strWarning = $strWarning + "Warning " + $objCertificate.SubjectName.Name.ToString() + " expires " + $objCertificate.NotAfter.ToString() + "`n"
	    $bReturnWarning = $TRUE
    }
    Else {
	    #Nothing for now
    }
}

If ($bReturnCritical) {
    write-output $strCritical
    write-output $strWarning "|" $DataTexte
    exit $returnStateCritical
}
Elseif ($bReturnWarning) {
    write-output $strWarning "|" $DataTexte
    exit $returnStateWarning
}
Else {
    write-output "OK" "|" $DataTexte
    exit $returnStateOK
}
