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 " -from “” -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: c# - FileSystemWatcher Changed event is raised twice - Stack Overflow

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

if the file has not been modified

Write-Host “Not Modified”