File watcher

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

  • Author
  • #19964
    Profile photo of fair64

    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 " -from "" -Subject "test" -smtp "smtpgateway"

  • #19965
    Profile photo of Dave Wyatt
    Dave Wyatt

    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:

  • #19968
    Profile photo of fair64

    Thanks Dave

  • #19974
    Profile photo of Adam Bertram
    Adam Bertram

    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

    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

    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 "" -from "" -Subject "Modified File detected" -smtp "smtpgateway"

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

You must be logged in to reply to this topic.