How check Updated File

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 8 months, 4 weeks ago.

  • Author
    Posts
  • #36341
    Profile photo of Vishal Joshi
    Vishal Joshi
    Participant

    Hi,
    I was trying to search a string in logs that will update continuously in every second.
    So i wrote the code to search the string if the string found in log it will triger an email.
    and created the tasks in task scheduler to run the script in every 5 min.
    But the issue is that if script found the "string" in log it will trigger mail in every 5 min continuoisly beause script is checking whole log file everytime.
    Can you please suggest me is this possible to point last script checked the logs till the point and next time script will run and do not check whole log file it will check only from last script done.

    $string = gci -path c:\folder\lofile.log | sort {$_.LastWriteTime} | select -last 1 | select-string -pattern "string"

    #####################################################################

    $fromaddress = "*************@gmail.com"
    $toaddress = "*************@gmail.com"
    $Subject = "testing"
    $body = "Hi Team`
    We got an error " +
    $string +
    "Please check"
    $attachment = "c:\folder\lofile.log"
    $smtpserver = "smtp.gmail.com"

    ####################################

    $message = new-object System.Net.Mail.MailMessage
    $message.From = $fromaddress
    $message.To.Add($toaddress)
    $message.IsBodyHtml = $True
    $message.Subject = $Subject
    $attach = new-object Net.Mail.Attachment($attachment)
    $message.Attachments.Add($attach)
    $message.body = $body
    $smtp = new-object Net.Mail.SmtpClient($smtpserver)
    $smtp.Send($message)

  • #36369
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Select-String doesn't have anything built in that would do what you want. I can think of a couple of ways I might do this, but none of them are going to perform very well if this file is large. I might look into using Get-Content with the -Tail option, to try and grab only the most recent lines from the file. You'd have to have some way of figuring out how many lines had been added since last time, I guess – I'm not sure how you'd go about that since I don't know what the log file contents look like.

You must be logged in to reply to this topic.