Search log files for specific word and sent an email alert

Hi all

I have 3 parts to a PowerShell script I am trying to create

I want to search the content of some log files for the previous 1 hour and if certain words are detected to send an email to let me know of an issue we have at the moment.

Apologies for the bad script, I know all 3 parts work individually as I have then in other scripts but unable to know how to link them together.

$Now = Get-Date
$LastwriteDev = $Now.Addhours(-1)

dir \\servername\SCMLogs -I *.txt, *.log -R | Select-String 'Access is denied Report Alert'

$smtp = "" 
$messagesubject= "Log Files ALert | $Now"
$messagebody= "Reports Error Found In Log Files!"

send-mailmessage -from "" -to $recipients -subject $messagesubject -BodyAsHtml $messagebody -Verbose -Smtpserver $SMTP

I will really be thankful of any help

Hmmm … do your log files have a time stamp in their file name or do the log entries inside the log files have a time stamp? You should share some sample file names or some sample log entries (formatted as code please).

How do you send an email? Your code snippet only defines some variables. :wink:

HI Olaf,

Thank you for the response, this is the error message I want to capture, and this is how it is written to a log in the below date and time format. The logs go over months, I could start new ones but ideally if I can just check the last 1 hour that would be most useful as there are 89 instances of this log file.

Event Type: Error
Time: 13 Dec 2021 16:21:42

Job ID: [ N/A ]
RemotingException Failed to create an IPC Port: Access is denied.

I have just added the line I missed from original post for send-mailmessage

The parameter -BodyAsHtml is a switch parameter. Usually you provide it without value on a command line. I’d use splatting for commands like Send-MailMessage anyway as ist makes your code easier to read and easier to maintain.

$SendMailMessageParams = @{
    From       = ''
    To         = ''
    Subject    = "Log Files ALert | $Now"
    Body       = "Reports Error Found In Log Files!"
    BodyAsHtml = $true
    Verbose    = $true
    SmtpServer = ''
Send-MailMessage @SendMailMessageParams

In “classical” log files one log entry fits on one line. In this case it would not be that hard to parse. If this is not a self created log file you will have to treat it according to the format and rythm of the log entries. To show only one entry will probably not be enough.
If you do create those log file by yourself I highly recommend to change the format to something easier to maintain. There are few frameworks you could use if you don’t want to create your own log system.
In most of my clients we use the SCCM CMTrace log format because we can use the logviewer for example.

This video gives a good overview over the possible options when parsing plain text data: