• Skip to primary navigation
  • Skip to main content
  • Skip to footer

Stephanos Constantinou Blog

PowerShell Scripting

  • Home
  • Blogs
    • PowerShell Tutorials
    • PowerShell Scripts
    • PowerShell Modules
      • Modules Cmdlets
    • Software Reviews
  • About
  • Contact
You are here: Home / PowerShell Scripts / Get Log File Changes

Get Log File Changes

07/09/2018 by Stephanos 1 Comment

Get Log File Changes

Scenario

Get Log File Changes

There are sometimes that we would like to know if there is a new content in a specific log file and we need to know the new content. The idea came out from Fasyx in a Reddit post. Below is the request of Fasyx exactly as provided in the post. 

I have a simple .log file which I want to monitor. I’m looking, if possible, for the following possibilities:

  1. ​Every time something gets appended to the file, an event should be raised. Given that a new line was appended, I also would like to be able to get the content of the appended line, so I can react on it.
  2. Contrary to the first approach, I don’t want to ‘watch’ the file all the time: I want to check it in a time interval (e.g. 3 minutes) and get the appended content since the last check.

Is something like this possible using powershell (keep in mind, I care about the file content)

In this post I will provide you with a simple script the is able to perform what Fasyx requested above. 

Script details

In general, the script will get the content of the log file and with the use of a temp file, it compares the content and it will provide the user with the differences. After the script will find the differences it will provide them to the pre-configured user. The script is quite static but it does the job.

[adinserter name=”In Article”]

Declaration of variables

First we will need to declare our variables that will be used during the process. The below variables are used to send the email to the user.

$PasswordFile variable includes the encrypted password of the user that will send the email. $Key variable includes the key to decrypt the content of $PasswordFile. $EmailUser includes the user that will authenticate in Exchage Online to send the email. $Password variable will include the password that will be used during the authentication with Exchange Online to send the email. $EmailCredentials variable will include the credentials object that we will use to send email. $To variable need to include all recipients that will get the email with the new content of the log file.

$From is the user that will sent the email. This is will be shown as from in the email. $EmailResult variable is an empty string. We ensure that the email that we will compose will not have any other value during the setup of email. $EmailUp and $EmailDown variables include part of the HTML code that will compose the HTML email report.

Code:

$PasswordFile = "C:\Scripts\Password.txt"
$Key = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32)
$EmailUser = "Script-User@domain.com"
$Password = Get-Content $PasswordFile | ConvertTo-SecureString -Key $Key
$EmailCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $EmailUser,$Password
$To = 'User1@domain.com','User2@domain.com'
$From = 'Script-User@domain.com'
$EmailResult = ""
$EmailUp = @"
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0D%0A%0D%0Abody%20%7B%20font-family%3ASegoe%2C%20%22Segoe%20UI%22%2C%20%22DejaVu%20Sans%22%2C%20%22Trebuchet%20MS%22%2C%20Verdana%2C%20sans-serif%20!important%3B%20color%3A%23434242%3B%7D%0D%0ATABLE%20%7B%20font-family%3ASegoe%2C%20%22Segoe%20UI%22%2C%20%22DejaVu%20Sans%22%2C%20%22Trebuchet%20MS%22%2C%20Verdana%2C%20sans-serif%20!important%3B%20border-width%3A%201px%3Bborder-style%3A%20solid%3Bborder-color%3A%20black%3Bborder-collapse%3A%20collapse%3B%7D%0D%0ATR%20%7Bborder-width%3A%201px%3Bpadding%3A%2010px%3Bborder-style%3A%20solid%3Bborder-color%3A%20white%3B%20%7D%0D%0ATD%20%7Bfont-family%3ASegoe%2C%20%22Segoe%20UI%22%2C%20%22DejaVu%20Sans%22%2C%20%22Trebuchet%20MS%22%2C%20Verdana%2C%20sans-serif%20!important%3B%20border-width%3A%201px%3Bpadding%3A%2010px%3Bborder-style%3A%20solid%3Bborder-color%3A%20white%3B%20background-color%3A%23C3DDDB%3B%7D%0D%0A.colorm%20%7Bbackground-color%3A%2358A09E%3B%20color%3Awhite%3B%7D%0D%0A.colort%7Bbackground-color%3A%2358A09E%3B%20padding%3A20px%3B%20color%3Awhite%3B%20font-weight%3Abold%3B%7D%0D%0A.colorn%7Bbackground-color%3Atransparent%3B%7D%0D%0A%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<style>" title="<style>" />
<body>
<h3>Script has been completed successfully</h3>
<h4>Log file changes:</h4>
<table>
    <tr>
   	    <td class="colort">Changes</td>
    </tr>
"@
$EmailDown = @"
</table>
</body>
"@

The next variables are related to the data that the script will process later. $LogFile variable will contain the path of the log file that we need to check. $Checkfile variable will contain the path of a file that we will have in order to compare the content of the file and then update it to keep always the current. $OldLogContent variable will content the content of the file that we keep for the comparison. $NewLogContent variable will contain the content of our log file. $Difference variable compares the two variables with the contact of the files and keeps an object with the differences.

Code:

$LogFile = "C:\SourcePath\LogFile.log"
$CheckFile = "C:\Scripts\Files\CheckFile.txt"
$OldLogContent = Get-Content -Path $CheckFile
$NewLogContent = Get-Content -Path $LogFile
$Difference = Compare-Object $OldLogContent $NewLogContent

[adinserter name=”In Article”]

Processing of data

After all variables have been configured and filled, the script will check if the $Difference variable is empty or not so we will continue to find the new content of the log file. If the variable is not empty, for each value we keep the content only, we add the content in our file that we keep for the comparison, and then we fill a temporary variable that will compile and complete the final email report. By adding each difference to our check file we ensure that we always keep the current logs for comparison.

Code:

if ($Difference -ne ""){
    Foreach ($DifferenceValue in $Difference){
        $DifferenceValueIndicator = $DifferenceValue.SideIndicator
        If ($DifferenceValueIndicator -eq "=>"){
            $NewContentOnly = $DifferenceValue.InputObject
            Add-Content -Path $CheckFile -Value $NewContentOnly
            $EmailTemp = @"
    <tr>
   	    <td>$NewContentOnly</td>
    </tr>
"@
            $EmailResult = $EmailResult + $EmailTemp}}}
$Email = $EmailUp + $EmailResult + $EmailDown

Get Log File Changes - 1

[adinserter name=”In Article”]

Send email report

After everything is ready we will send our email report. The script will check if the email is emprty or not. If the email is empty, no email will be send to the recipients. If there differences then an email will be send containing each difference in a new line. Currently the script uses Exchange Online to send emails. If you have a different setup you will need to your own settings to send the email.

Code:

if ($EmailResult -ne ""){
    $EmailParameters = @{
        To = $To
        Subject = "Log File Changed $(Get-Date -format dd/MM/yyyy)"
        Body = $Email
        BodyAsHtml = $True
        Priority = "High"
        UseSsl = $True
        Port = "587"
        SmtpServer = "smtp.office365.com"
        Credential = $EmailCredentials
        From = $From}
    send-mailmessage @EmailParameters
}

Get Log File Changes - 4

Get Log File Changes - 3

Get Log File Changes - 2

You can download the script here or copy it from below. (Note that code within the script might not be copied correctly due to syntax highlighting.)

Hope you like it.

You feedback is appreciated.

If you have any questions or anything else please let me know in the comments below.

[adinserter name=”In Article”]

Related Links

  • PowerShell Scripts
  • PowerShell Tutorials
  • Encrypt password with key using PowerShell
  • Send Email using PowerShell
  • Get-Content – Microsoft Docs
  • ConvertTo-SecureString – Microsoft Docs
  • New-Object – Microsoft Docs
  • Compare-Object – Microsoft Docs
  • Add-Content – Microsoft Docs
  • Get-Date – Microsoft Docs
  • Send-MailMessage – Microsoft Docs

[adinserter name=”In Article”]

Solution / Script

<#
.SYNOPSIS
  Name: Get-LogFileChanges.ps1
  The purpose of this script is to monitor and inform you when there is new information in a log file.
.DESCRIPTION
  This is a simple script that needs to be configured as a Scheduled task or schedule job in order to
  monitor a specific log file and any additional entry.
.RELATED LINKS
  
Home
.NOTES Version: 1.0 Release Date: 06-09-2018 Author: Stephanos Constantinou .EXAMPLE Run the Get-LogFileChanges.ps1 script. .\Get-LogFileChanges.ps1 #> $PasswordFile = "C:\Scripts\Password.txt" $Key = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32) $EmailUser = "Script-User@domain.com" $Password = Get-Content $PasswordFile | ConvertTo-SecureString -Key $Key $EmailCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $EmailUser,$Password $To = 'User1@domain.com','User2@domain.com' $From = 'Script-User@domain.com' $LogFile = "C:\SourcePath\LogFile.log" $CheckFile = "C:\Scripts\Files\CheckFile.txt" $EmailResult = "" $OldLogContent = Get-Content -Path $CheckFile $NewLogContent = Get-Content -Path $LogFile $Difference = Compare-Object $OldLogContent $NewLogContent $PasswordFile = "C:\Scripts\Password.txt" $Key = (5,10,20,40,80,160,2,4,8,16,32,64,128,3,6,12,24,48,96,192,7,14,28,56,112,224,9,18,36,72,144,1) $EmailUser = "ITOperations-Monitoring@bs-shipmanagement.com" $Password = Get-Content $PasswordFile | ConvertTo-SecureString -Key $Key $EmailCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $EmailUser,$Password $To = 'stephanos.constantinou@bs-shipmanagement.com' $From = 'ITOperations-Monitoring@bs-shipmanagement.com' $EmailUp = @" <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0D%0A%0D%0Abody%20%7B%20font-family%3ASegoe%2C%20%22Segoe%20UI%22%2C%20%22DejaVu%20Sans%22%2C%20%22Trebuchet%20MS%22%2C%20Verdana%2C%20sans-serif%20!important%3B%20color%3A%23434242%3B%7D%0D%0ATABLE%20%7B%20font-family%3ASegoe%2C%20%22Segoe%20UI%22%2C%20%22DejaVu%20Sans%22%2C%20%22Trebuchet%20MS%22%2C%20Verdana%2C%20sans-serif%20!important%3B%20border-width%3A%201px%3Bborder-style%3A%20solid%3Bborder-color%3A%20black%3Bborder-collapse%3A%20collapse%3B%7D%0D%0ATR%20%7Bborder-width%3A%201px%3Bpadding%3A%2010px%3Bborder-style%3A%20solid%3Bborder-color%3A%20white%3B%20%7D%0D%0ATD%20%7Bfont-family%3ASegoe%2C%20%22Segoe%20UI%22%2C%20%22DejaVu%20Sans%22%2C%20%22Trebuchet%20MS%22%2C%20Verdana%2C%20sans-serif%20!important%3B%20border-width%3A%201px%3Bpadding%3A%2010px%3Bborder-style%3A%20solid%3Bborder-color%3A%20white%3B%20background-color%3A%23C3DDDB%3B%7D%0D%0A.colorm%20%7Bbackground-color%3A%2358A09E%3B%20color%3Awhite%3B%7D%0D%0A.colort%7Bbackground-color%3A%2358A09E%3B%20padding%3A20px%3B%20color%3Awhite%3B%20font-weight%3Abold%3B%7D%0D%0A.colorn%7Bbackground-color%3Atransparent%3B%7D%0D%0A%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<style>" title="<style>" /> <body> <h3>Script has been completed successfully</h3> <h4>Log file changes:</h4> <table> <tr> <td class="colort">Changes</td> </tr> "@ $EmailDown = @" </table> </body> "@ if ($Difference -ne ""){ Foreach ($DifferenceValue in $Difference){ $DifferenceValueIndicator = $DifferenceValue.SideIndicator If ($DifferenceValueIndicator -eq "=>"){ $NewContentOnly = $DifferenceValue.InputObject Add-Content -Path $CheckFile -Value $NewContentOnly $EmailTemp = @" <tr> <td>$NewContentOnly</td> </tr> "@ $EmailResult = $EmailResult + $EmailTemp}}} $Email = $EmailUp + $EmailResult + $EmailDown if ($EmailResult -ne ""){ $EmailParameters = @{ To = $To Subject = "Log File Changed $(Get-Date -format dd/MM/yyyy)" Body = $Email BodyAsHtml = $True Priority = "High" UseSsl = $True Port = "587" SmtpServer = "smtp.office365.com" Credential = $EmailCredentials From = $From} send-mailmessage @EmailParameters }

[adinserter name=”Matched-Content”]

Summary
Get Log File Changes
Article Name
Get Log File Changes
Description
Get Log File Changes. Here you will find information about a PowerShell script to Get Log File Changes . Stephanos Constantinou Blog
Author
Stephanos
Publisher Name
Stephanos Constantinou Blog
Publisher Logo
Stephanos Constantinou Blog

Filed Under: PowerShell Scripts Tagged With: Add-Content, Compare-Object, ConvertTo-SecureString, Get-Content, Get-Date, New-Object, Send-MailMessage

Reader Interactions

Comments

  1. Artur Tyksinski says

    26/10/2019 at 18:05

    Great script, thank you for sharing. I’m sure this will come in useful one day for me

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Footer

Recent Posts

  • ICS Cube Product Review 26/04/2019
  • PowerShell Module SysInfo v1.2.0 15/03/2019
  • PowerShell Module SysInfo v1.1.2 13/11/2018
  • PowerShell Module SysInfo 24/10/2018
  • Get-VoltageProbe 24/10/2018
  • Get-VideoController 24/10/2018
  • Get-USBController 24/10/2018
  • Get-TrackPoint 24/10/2018
  • Get-TrackBall 24/10/2018
  • Get-TouchScreen 24/10/2018
Planet PowerShell

Categories

  • Modules Cmdlets (57)
  • PowerShell Modules (5)
  • PowerShell Scripts (38)
  • PowerShell Tutorials (35)
  • Software Reviews (2)

Archives

  • April 2019 (1)
  • March 2019 (1)
  • November 2018 (1)
  • October 2018 (56)
  • September 2018 (13)
  • August 2018 (9)
  • July 2018 (6)
  • June 2018 (8)
  • May 2018 (7)
  • April 2018 (9)
  • March 2018 (4)
  • February 2018 (6)
  • January 2018 (12)
  • December 2017 (4)
Top 10 PowerShell 2018

Blogroll

  • Planet PowerShell
  • Reddit – PowerShell
  • PowerShell Magazine
  • PowerShell.org
  • PowerShell Team Blog
  • Hey, Scripting Guy! Blog
  • Mike F Robbins
  • PowerShell Explained with Kevin Marquette
  • Mike Kanakos – Network Admin
  • The Lonely Administrator
  • AskME4Tech
PowerShell Blogs Sysadmin Blogs Banners for Top 20 Programming Blogs

© 2023 · Stephanos Constantinou Blog

  • Home
  • Blogs
  • About
  • Contact