This is my PowerShell log file parser with email alert – it’s a bit rough, could do with some optimizing, but a quick overview – it searches for the text string ‘warn’ or ‘error’.

You will need to adjust the structure of the log files and folder to make them suit your application, and you must set the SMTP settings towards the bottom of the script:

 

#delete the log file

echo “Deleting log file..”

#this is a temporary log file
$logfile = “c:\batch\log_warn.txt”
if(!(Test-Path -Path $logfile))
{
#file does not exist
echo “File $logfile does not exist”
}
else
{
Remove-Item $logfile
echo “file $logfile deleted”
}

# get date in the correct format for the folder
$folderdate = get-date -format “yyyy-MM”
# get date in the correct format for the file
$filedate = get-date -format “yyyy-MM-dd”

# build the full path
$fullpath = “C:\ProgramData\program\logs\$folderdate\aslog-$filedate.log”
echo “Using $fullpath”

#set email flag to false
$email_flag=$false

#check the file exists
if(!(Test-Path -Path $fullpath))
{
#file does not exist
echo “File does not exist”
$email_flag=$true
$email_subject=”File Does Not Exist – $fullpath”
}
else
{

#file exists
#search in the latest file for the strings warn or error:
dir $fullpath | Select-String warn,error | Out-File $logfile

#get the file size to see if it contains any data
$var = Get-Item $logfile
$var_length=$var.length
echo “File Size (bytes): $var_length”
#an empty file has a size of 2 bytes

#if >2 bytes, then we have found errors
if($var_length -gt 2)
{
#email the file off
echo “File greater than 2 – warnings found”
$email_flag=$true
$email_subject=”Warnings or errors found in $fullpath”
}
else
{
echo “File not greater than 2, no errors”
$email_flag=$true
$Email_Subject = “No warnings or errors found in $fullpath”
}

}

if($email_flag -eq $true)
{

$EmailFrom = “powershell_log_checker@yourdomain.co.uk”
$EmailTo = “someone@domain.com”
$EmailBody = “See $fullpath for errors”

$SMTPServer = “mail.your-smtp-server.co.uk”
$SMTPPort = “25”

echo “Emailing $EmailTo”
echo $email_subject

# Send E-mail message with log file attachment
$Message = New-Object Net.Mail.MailMessage($EmailFrom, $EmailTo, $Email_Subject, $EmailBody)
#$Attachment = New-Object Net.Mail.Attachment($Logfile, ‘text/plain’)
#$Message.Attachments.Add($Attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, $SMTPPort)
$SMTPClient.Send($Message)

}
else
{
echo “not emailing”
}

You must be logged in to leave a reply.