Powershell get dates from log file,  compare with current date and set an alert/e-mail notification

dfke
dfke used Ask the Experts™
Hi,

I have a log file with output in the following format. I put xxxxxxxx because the log contains sensitive data.
There are multiple sections like this one and all are separated by a blank line.

I wish to receive an e-mail/set an alert when if any of the dates in the log are more than 24 hours ago. Just trying to figure out how to read and compare the dates with the current date.

xxxxxxxx                                            : xxxxxxxx
xxxxxxxx                                            : xxxxxxxx
xxxxxxxx                                            : xxxxxxxx
xxxxxxxx                                            : 1/14/2020 5:30:08 AM
xxxxxxxx                                            : 1/14/2020 5:30:06 AM
xxxxxxxx                                            : 1/14/2020 5:30:04 AM
xxxxxxxx                                            : 1/14/2020 5:30:08 AM

Open in new window


If anyone can get me in the right direction if would be very much appreciated.

Cheers
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Something like this?
$logFile = '.\test.log'
$warnDate = (Get-Date).AddHours(-24)

$dtProvider = New-Object -TypeName System.Globalization.CultureInfo -ArgumentList 'en-US'
$line = 0
$body = New-Object -TypeName System.Collections.ArrayList
Get-Content -Path $logFile | ForEach-Object {
	$line += 1
	If (($_ -match '(?<Date>\b\d{1,2}/\d{1,2}/\d{4}\s\d{1,2}:\d{2}:\d{2}\s(A|P)M$)') -and ([DateTime]::Parse($Matches['Date'], $dtProvider) -lt $warnDate)) {
		[void]$body.Add($_)
		Write-Warning "Critical date in line $($line): $($_)!"
	}
}
If ($body.Count -gt 0) {
	$mailArgs = @{
		From = 'someone@domain.com'
		To = 'someone.else@domain.com'
		Subject = 'Found critical date(s) in log file'
		Body = "Found critical date(s):`r`n" + ($body -join "`r`n")
		Attachments = $logFile
		SmtpServer = 'smtp.domain.com'
	}
	Send-MailMessage @mailArgs
}

Open in new window

Hi oBdA,

That's perfect! Thanks for your quick reply!

Cheers

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial