Forum Discussion

Alexandros8888's avatar
Alexandros8888
Copper Contributor
Jan 08, 2021

Task scheduler messes up date format in my PowerShell script

Hello I have the following PowerShell script that calculates expired certificates and sends email about it.

 

 

 

$Urls = @()
$Urls = "https://....",
"https://......",
"https://...."

$Result = @()

$MinimumCertAgeDays = 5000
$dummy = 0
$count = 1
$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 )
 {  
 
 $dummy = 1


 $Result += "
   $count) Certificate for Host: $url  Expires on ----->  $ExpirationDate    Expires in ----->  $DayCount DAYS `n "  
                                                                                     
  $count = $count + 1

 }

}

If ($dummy -eq 1 )
 {
 

   # Sender and Recipient Info
   $MailFrom = "myemail"
   $MailTo = "myemail"

   # Sender Credentials
   $Username = "myusername"
   $Password = "mypass"

   # Server Info
   $SmtpServer = "myserver"
   $SmtpPort = "myport"

   # Message stuff
   $MessageSubject = "!!!!!!!!!!!!!!SOS CERTIFICATES ARE GOING TO EXPIRE!!!!!!!!!!!!!!!!!!" 
   $Message = New-Object System.Net.Mail.MailMessage $MailFrom,$MailTo
   #$Message.IsBodyHTML = $true
   $Message.Subject = $MessageSubject
   $Message.Body = $Result
   $Message.Priority = "high"  

   # 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)
}

 

 

 

The script runs successfully when i trigger it from Powershell ISE and i got the following email as exactly i wanted (please look image 1 below)

IMAGE 1

 

Nevertheless when i run the exact same script BUT this time through task scheduler in windows (in order to automate this procedure) i get the following results (please see image 2 below)

IMAGE2

 

So as it can be detected by image 2, through task scheduler i get a crazy negative number of days remaining for expiration and also the πμ word in Greek :).

 

Can somebody may help on how to resolve that problem?

 

Best regards,

Alexandros

Resources