Hello everyone,
I'm relatively new to PS. I'm working on a script which mails a list of certificates, which expire within 30 days.
The problem is, I think, he compares the "Certificate Expire Date" in the wrong format. He gives me a list where the expiration date is in the format MM/dd/yyyy, when both my pc and server are in format dd/MM/yyyy.
Can someone help me sort this out?
Here's the script:
# variables
$datestring = (Get-Date).ToString(“yyyyMMdd”).Replace(“:”,”-”)
$filesave = “d:\CertMGMT\CertExport_$datestring.csv”
[string]$caServerName = "CA-location"
[string]$caCertExportPath = "$filesave"
[string]$smtpSender = "sender@yourdomain.com"
[string]$smtpRecipient = "receiver@yourdomain.com"
[string]$smtpServer = "Mailserver"
[int]$daysUntilExpiry = 30
$expiringCerts = @()
function Send-EmailCertNotice ([string]$_certificateList) {
$MailMessage = @{
To = $smtpRecipient
From = $smtpSender
Subject = @"
The following issued digital certificates will expire soon.
"@
Body = @"
The following digital certificates issued by (company) will expire in the next $daysUntilExpiry days.
Please send a request for a certificate replacement/renewal to the users, if the following certificates are still needed.
$_certificateList
NOTE: This notification is being sent by an automated certificate management process and
cannot receive reply e-mail. If you have any questions please contact your system administrator.
"@
Smtpserver = $smtpServer
BodyAsHtml = $false
ErrorAction = "SilentlyContinue"
}
Send-MailMessage @MailMessage
}
# export certs to CSV file
certutil -view -restrict "Public Key Length=2048,Request Disposition=20" -config $caServerName csv > $caCertExportPath
# load cert CSV into an array
$issuedCerts = Import-Csv $caCertExportPath
if ($issuedCerts.Length -gt 0) {
foreach ($cert in $issuedCerts) {
try {
$certExpires = [datetime]$cert."Certificate Expiration Date"
$cert."Certificate Expiration Date" = $certExpires
}
catch [Exception] {
}
if ($certExpires -gt $(Get-Date) -and $certExpires -lt $(Get-Date).AddDays($daysUntilExpiry)) {
# filter out revoked and only smartcarduser certs.
if ($cert."Issued Organization Unit" -ne "EMPTY"
) {
$expiringCerts += $cert
}
}
}
$bodyVal = $expiringCerts | Select-Object @{n="Certificate ID"; e="Request ID"},
"Certificate Expiration Date", "Issued Common Name" | Sort-Object { $_."Certificate Expiration Date" -as [datetime] } | Out-String
Send-EmailCertNotice $bodyVal
}