0

I'm using a FileWatcher script and everything seems to be working as far as monitoring. The problem is that when a file changes, it's set to send me an email. It emails out fine but always sends 2 emails or if i'm sending to a text, 2 texts. What's going on here? Here's my code:

$fswAuctions = New-Object IO.FileSystemWatcher $auctions, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fswAuctions Changed -SourceIdentifier FilesChanged4 -Action {

$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated

$SMTPBody = "The file '$name' was $changeType at $timeStamp"
Send-ToEmail -email "myemail@whatever.com" -strBody $SMTPBody -strSubject "Auctions Module"
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white

}

function Send-ToEmail([string]$email, [string]$strBody, [string]$strSubject){

    $message = new-object Net.Mail.MailMessage
    $message.From = "do_not_reply@site.com"
    $message.To.Add($email)
    $message.Subject = $strSubject
    $message.Body = $strBody

    $smtp = new-object Net.Mail.SmtpClient("127.0.0.1", "25")
    $smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
    $smtp.send($message)
 }
halfer
  • 19,824
  • 17
  • 99
  • 186
Damien
  • 4,093
  • 9
  • 39
  • 52
  • Did you check whenever there are just two events that are being generated? – Seth Oct 11 '18 at 11:12
  • 1
    from my research, editing a file raises multiple events. i guess the question is, how do I make multiple events for the same thing count as one? – Damien Oct 11 '18 at 13:37
  • 1
    If you look at the documentation for [NotifyFiter](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.notifyfilter?view=netstandard-2.0) it looks like you might just be listening to multiple events. Maybe just use one of them. If you only want to mail every so often you could go with a queue and periodically use the information of the queue to generate mails. – Seth Oct 12 '18 at 05:19

0 Answers0