I want to watch if the file is changed:
$path = "C:\2"
$i=0
$w=new-object io.filesystemwatcher
$w.path=$path
$w.filter="test.txt"
register-objectevent $w Changed -action {
write-host $event.sourceeventargs.fullpath
$i++
write-host $i
}
cls
sleep 2
777 >c:\2\test.txt # Event of the file changing
Output:
C:\2\test.txt
1
C:\2\test.txt
2
Why i got one event twice?
Update.
Fix attempt:
$path = "C:\2"
$i=0
$w=new-object io.filesystemwatcher
$w.path=$path
$w.filter="test.txt"
register-objectevent $w Changed -action {
$i++
if($i%2 -eq 0){
write-host "Here"
write-host $event.sourceeventargs.fullpath
}
}
cls
sleep 2
777 >c:\2\test.txt
Output:
Here
C:\2\test.txt
Is it the best way to fix it?