0

Here is the PowerShell Script so far:

It monitors the folder specified beautifully but generates two entries on file changes.

Is there a way to consolidate or just return one event?

Get-EventSubscriber | Unregister-Event

$fsw = New-Object System.IO.FileSystemWatcher

$fsw.Path = 'c:\ftptest'
$fsw.Filter = '*.*'
$fsw.EnableRaisingEvents = $true
$fsw.IncludeSubdirectories = $true
$fsw.NotifyFilter = [IO.NotifyFilters]::LastWrite


$null = Register-ObjectEvent -InputObject $fsw -EventName Changed -SourceIdentifier MonitorFiles 

while ($true)
{
    $evt = Wait-Event -SourceIdentifier MonitorFiles

    Write-Host "Changed: $($evt.SourceEventArgs.FullPath)"

    $evt | Remove-Event

}

When I edit a file and save it, it outputs the file changed twice. Changed: c:\ftptest\Test1.txt Changed: c:\ftptest\Test1.txt

Ok I have changed the code to this which seems to help - a kind of flip-flop if you will...

Get-EventSubscriber | Unregister-Event

$fsw = New-Object System.IO.FileSystemWatcher

$fsw.Path = 'c:\ftptest'
$fsw.Filter = '*.*'
$fsw.EnableRaisingEvents = $true
$fsw.IncludeSubdirectories = $true
$fsw.NotifyFilter = [IO.NotifyFilters]::LastWrite


$null = Register-ObjectEvent -InputObject $fsw -EventName Changed -SourceIdentifier MonitorFiles 

$Buffer = ""

while ($true)
{
    $evt = Wait-Event -SourceIdentifier MonitorFiles

    if ($Buffer -eq "Changed: $($evt.SourceEventArgs.FullPath)") {

        $Buffer = ""

    } Else {

        $Buffer = "Changed: $($evt.SourceEventArgs.FullPath)"

    }

    Write-Host $Buffer.ToString()

    $evt | Remove-Event

}
XantorAmnobius
  • 93
  • 1
  • 10
  • What is the result displayed when it _"generates two entries on file changes"_? – Manu Nov 23 '17 at 09:13
  • Changed: c:\ftptest\Test1.txt Changed: c:\ftptest\Test1.txt – XantorAmnobius Nov 23 '17 at 09:17
  • You should add the result displayed by editing your question so others can see it immediately – Manu Nov 23 '17 at 09:23
  • My next step would be to not just output the path that has changed, but the details of what has changed. It is probably changing two properties of the same file so you get two results. If you can narrow it down to only return results for a specific property or properties, this may resolve your issue. NOTE: This is just a guess... – Ross Lyons Nov 23 '17 at 09:37
  • I have to add that I'm a complete noob to PowerShell. How will I achieve determining what has changed? – XantorAmnobius Nov 23 '17 at 09:45
  • Use `Compare-Object`. – Moerwald Nov 23 '17 at 10:05
  • This is a very common issue. See https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice – andyb Nov 24 '17 at 06:10

0 Answers0