File watcher

Welcome Forums General PowerShell Q&A File watcher

This topic contains 5 replies, has 3 voices, and was last updated by

 
Participant
4 years, 4 months ago.

  • Author
    Posts
  • #19964

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    Thanks Dave

  • #19974

    Participant
    Points: 22
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

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

  • #20019

    Participant
    Points: 0
    Rank: Member

    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"
    }

The topic ‘File watcher’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort