File watcher

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of fair64 fair64 2 years, 1 month ago.

  • Author
    Posts
  • #19964
    Profile photo of fair64
    fair64
    Participant

    I am trying to set up a script that will email me when it has been modified. The script works fine except that I receive two emails per change. Any clues on how to fix this?
    Thanks in advance.

    $fileWatcher = New-Object System.IO.FileSystemWatcher
    $fileWatcher.Path = "C:\watch"

    Register-ObjectEvent -InputObject $fileWatcher -EventName Changed -SourceIdentifier File.Changed -Action {
    $Global:t = $event
    Write-Host ("File Changed: {0} on {1}" -f $event.SourceEventArgs.Name,
    (Split-Path $event.SourceEventArgs.FullPath))
    Send-MailMessage -Body "$body" -to "to@email.com -from "email@test.com" -Subject "test" -smtp "smtpgateway"
    }

  • #19965
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That's a common complaint with the FileSystemWatcher, which basically comes from the fact that many file system operations are actually combinations of multiple steps, from the Win32 API's point of view. You can find several workarounds for this over on StackOverflow: http://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice

  • #19968
    Profile photo of fair64
    fair64
    Participant

    Thanks Dave

  • #19974
    Profile photo of Adam Bertram
    Adam Bertram
    Participant

    Probably not the best answer but you could code in a counter in there and use the modulus operator to only send emails upon even or odd numbered iterations.

  • #19986
    Profile photo of fair64
    fair64
    Participant

    Hi Adam,
    I was thinking about doing something like that but wasn't sure how to incorporate this into the code (still learning)...

  • #20019
    Profile photo of fair64
    fair64
    Participant

    This is what I ended up doing:
    $file = (Get-Item C:\watch\me.txt).LastWriteTime.ToString("MM/dd/yyyy HH:mm:ss")
    #$file.LastWriteTime.ToString("MM/dd/yyyy HH:mm:ss") | out-file C:\watch\timestamp.txt
    $orgfile = Get-Content C:\watch\timestamp.txt

    # if file has been modified
    if ($file -gt $orgfile)
    {
    $file | out-file C:\watch\timestamp.txt
    Write-Host "Modified"
    Send-MailMessage -Body "File has been modified on $file" -to "admin@email.com" -from "filemodifier@email.com" -Subject "Modified File detected" -smtp "smtpgateway"
    }

    # if the file has not been modified
    else
    {
    Write-Host "Not Modified"
    }

You must be logged in to reply to this topic.