2

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?

Lexxy
  • 457
  • 2
  • 11

1 Answers1

2

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

Gerrit Geeraerts
  • 924
  • 1
  • 7
  • 14
  • Is it the best way of the fix in the Q post? – Lexxy Jun 25 '20 at 11:21
  • It depends on the context: what is inside test.txt? What process is writing to it? And what action do you want to perform when your detection a change? Or are you just playing arround with powershell and testing some stuff out? – Gerrit Geeraerts Jun 25 '20 at 21:01
  • This is a very robust solution: https://stackoverflow.com/a/3042963/10213635 You can also find some other solutions their – Gerrit Geeraerts Jun 25 '20 at 21:09