If my logic is right I think this should work, this script would run indefinitely.
For sending Mails in PowerShell you have two options that I'm aware of, one is using the cmdlet designed for that: Send-MailMessage
However, this is important to be aware of:
Warning
The Send-MailMessage
cmdlet is obsolete. This cmdlet does not guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage
. For more information, see Platform Compatibility note DE0005.
You can find the second option here using Net.Mail.MailMessage
.
Now for the code of the script, here is something you can use:
# Define the full path of your logs folder
$logsFolder = 'fullPath\to\logsFolder'
# Function for monitoring and retrieving the newest log file Full Path
function Get-NewestLog ($LogPath) {
Get-ChildItem $LogPath -Filter *.txt | Sort-Object CreationTime -Descending |
Select-Object -First 1 -ExpandProperty FullName
}
# Get the newest log file
$logFilePath = Get-NewestLog -LogPath $logsFolder
while($true) {
# If we don't have today's date stored
# or the update trigger is True
if($updateDate -or -not $today) {
$today = [datetime]::Today
$updateDate = $false
}
if($today -lt [datetime]::Today) {
# Trigger our previous condition
$updateDate = $true
# Get the new log file for this day
$logFilePath = Get-NewestLog -LogPath $logsFolder
}
if((Get-Content $logFilePath -Raw) -match 'Error') {
# Send mail message goes here
}
Start-Sleep -Seconds 60
}
It is important to note that, this would spam your inbox every minute if there is an error in the log file so it will probably be a good idea to add a new condition in this block:
if((Get-Content $logFilePath -Raw) -match 'Error') {
....
}
For example something like this:
if((Get-Content $logFilePath -Raw) -match 'Error' -and -not $emailSentThisDay) {
# Send mail message goes here
# Here you set this bool to True so you don't get spammed :D
$emailSentThisDay = $true
}
If this is something you will consider then you will need to reset the $emailSentThisDay
bool every new day so:
if($today -lt [datetime]::Today) {
# Trigger our previous condition
$updateDate = $true
# Reset the antispam bool if this is a new day
$emailSentThisDay = $false
# Get the new log file for this day
$logFilePath = Get-NewestLog -LogPath $logsFolder
}