Root Loop
Root Loop

Reputation: 3162

Using Powershell to monitor a log file in real time and send an message if found any matches

I am using Powershell to monitor a LOG file and filtering certain key words, need some help to put below lines all together and make it working as an automated task for alert.

Get-Content D:\temp\wow.log -Wait | where {$_ -match "TROUBLE CONNECTING!!"}
$LastWriteTime = (Get-Item $LogFile).LastWriteTime
$CurrentTime = Get-Date
$Range = (New-TimeSpan -Start $LastWriteTime -End $CurrentTime).TotalMinutes

Questions:

  1. How can I use -wait with if the key words found
  2. between the time range from LastWriteTime till CurrentTime
  3. then, send a message.

I am trying to make it as a real time alert, not filtering the entire log but only the newest event.

If I want to schedule it as a task without output to screen, what are my options?

This is the message in the log file

WARN    server  comment 2021-06-11  02:21:01    -   -   -   -   -   2.0650160216E7  -   -   -   -   -   -   -   -   PushPublishRTMP.Reconnector[url]: TROUBLE CONNECTING!! Retrying in 60 seconds. app:live/_definst_

Upvotes: 1

Views: 7576

Answers (1)

mklement0
mklement0

Reputation: 440471

Get-Content -Wait runs indefinitely or until the target file is deleted, moved or renamed (or, interactively, until Ctrl-C is pressed or the console window is closed).

It polls the specified file for new lines every second and outputs them to the pipeline.

Therefore, you need to perform processing as part of the same pipeline, using a ForEach-Object call:

Get-Content D:\temp\wow.log -Wait -Last 0 |
 Where-Object { $_ -match 'TROUBLE CONNECTING!!' } |
  ForEach-Object {
    # Send an email here, e.g.:
    # Send-MailMessage -SmtpServer exchange.example.com -From [email protected] -To [email protected] -Subject 'Connection error' -Body $_
  }

Note:

  • -Last 0 means that preexisting content in the file is ignored, and that only lines added after starting the command are output. I'm assuming this addresses your time-window need, but I'm not sure of your exact requirements.

  • You can use Send-MailMessage to send emails, but note that this cmdlet is considered obsolete, because it "does not guarantee secure connections to SMTP servers." That said, if that isn't a concern in your case, it is fine to use, and, given PowerShell's commitment to backward compatibility, the cmdlet is unlikely to ever be removed.

Upvotes: 5

Related Questions