File watcher

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

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

Thanks Dave

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.

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

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