I have a log file and I am trying not to capture the same error in the log when the below script runs. The script is running every 5 minutes through task scheduler. (so, if there are new entries with the specific error an email should be sent, if not then nothing to do - it shouldn't read the whole log) The goal is to store the last time the log was checked with a time stamp. If there is no new entry (of the same error) when the script runs then there is nothing to do. (shouldn't send an Email) Else it should send an Email.
The log looks like:
2021-01-05 15:44:45
CODE : 00002
LEVEL : 4
NAME : com.apps.common.util.ApplicationException
ERROR # : UTUD3SIQY3Z0
TOKEN ID : 2574333
USER : System
MESSAGE : The requested operation could not be completed.
at com..apps.common.util.LoggingHelper.logError(LoggingHelper.java:128)
at com..apps.common.util.ErrorHandler.log(ErrorHandler.java:644)
at com..apps.common.util.ErrorHandler.handleError(ErrorHandler.java:131)
What I have tried so far but without success is this:
$File = 'D:......\logs\Nikos_text2.txt'
$content = Get-Content $File
While($true){
$date = (Get-Date).AddMinutes(-5)
$Writetime = Get-Item $File | select lastwritetime | get-date
If ($Writetime -le $date -and $content -like 'Trigger action error'){
$smtp = new-object Net.Mail.SmtpClient("server name")
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "support@keyman .com"
$objMailMessage.To.Add("support@keyman .com")
$objMailMessage.To.Add("support@keyman .com")
$objMailMessage.Subject = "Error message: 'Trigger action error'"
$objMailMessage.Body = "In log in server (SI) I traced the following error message: Trigger action error. Pls check it asap"
$smtp.send($objMailMessage)
}
Start-Sleep -Seconds 300
}
From my understanding either I should capture every time the script runs the last line of the log that previously run or put a timestamp and the next time it will run, then to check for errors after the last timestamp. But due to the fact that I am brand new to Powershell, I don't have a clue how to achieve it.
Any help would be much appreciated.
Thank you in advance
I now made some changes to my code:
$time = '{0:yyyy-MM-dd HH:mm:ss}' -f (Get-Date '2021-02-02 12:40:48').AddMinutes(-5)
$File = 'D:......\logs...log'
$search = 'Application Error*'
$query = (Get-Content $File) | Where-Object {$-match $search} | Select-Object -Last 1
if ($query -match "Application Error*" -and ($ -split ',')[0] -gt $time) {
$smtp = new-object Net.Mail.SmtpClient("server")
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "support@keyman .com"
#$objMailMessage.To.Add("support@keyman .com")
$objMailMessage.To.Add("support@keyman .com")
$objMailMessage.Subject = "Error message: 'Application error'"
$objMailMessage.Body = "In log in server I traced the following error message: Application error"
$smtp.send($objMailMessage)
}
but still I am not able to receive an Email notification.