Powershell fileSystemWatcher Events

Viewed 199

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?

1 Answers

777 > c:\2\test.txt This command actualy changes the content 2 times:

  1. it erases the content
  2. it adds 777 to the content of the file

777 >> c:\2\test.txt only changes the contents once by appending 777 to the file

You could see other funky behaviors with this, for example some application might write in batches to the file instead of in 1 time so you could get even more triggers.

This is a very robust solution: https://stackoverflow.com/a/3042963/10213635 You can also find some other solutions their

Related