当应用程序更改文件时 FileSystemWatcher 不会监听事件

当应用程序更改文件时 FileSystemWatcher 不会监听事件

我有一个 Powershell Core 脚本,用于FileSystemWatcher递归监听目录中的更改。当用户使用 Windows 资源管理器或 shell 添加或修改文件时,它的行为符合预期。但是,当 Java 应用程序添加或修改文件时,不会听到任何事件。我猜是 shell 和 Explorer 做了应用程序没有做的事情。我发现了一个旧的超级用户帖子抱怨非 Java 应用程序中的相同行为。

我该如何纠正这个问题?

我正在使用 Windows 10 Pro,版本 18362,Powershell 版本 7.0.0,Java 版本“10.0.2”2018-07-17

FileSystemWatcher这是我用来创建并注册的函数Register-ObjectEvent

Function Start-FileSystemWatcher {
    [cmdletbinding()]
    Param (
        [parameter()]
        [string]$Path,
        [parameter()]
        [ValidateSet('Changed', 'Created', 'Deleted', 'Renamed')]
        [string[]]$EventName,
        [parameter()]
        [string]$Filter,
        [parameter()]
        [System.IO.NotifyFilters]$NotifyFilter,
        [parameter()]
        [switch]$Recurse,
        [parameter()]
        [scriptblock]$Action
    )
    $FileSystemWatcher = New-Object System.IO.FileSystemWatcher
    If (-NOT $PSBoundParameters.ContainsKey('Path')) {
        $Path = $PWD
    }
    $FileSystemWatcher.Path = $Path
    If ($PSBoundParameters.ContainsKey('Filter')) {
        $FileSystemWatcher.Filter = $Filter
    }

    If ($PSBoundParameters.ContainsKey('NotifyFilter')) {
        $FileSystemWatcher.NotifyFilter = $NotifyFilter
    }
    If ($PSBoundParameters.ContainsKey('Recurse')) {
        $FileSystemWatcher.IncludeSubdirectories = $True
    }
    If (-NOT $PSBoundParameters.ContainsKey('EventName')) {
        $EventName = 'Changed', 'Created', 'Deleted', 'Renamed'
    }
    If (-NOT $PSBoundParameters.ContainsKey('Action')) {
        $Action = {
            Switch ($Event.SourceEventArgs.ChangeType) {
                'Renamed' {
                    $Object = "{0} was {1} to {2} at {3}" -f $Event.SourceArgs[-1].OldFullPath,
                    $Event.SourceEventArgs.ChangeType,
                    $Event.SourceArgs[-1].FullPath,
                    $Event.TimeGenerated
                }
                Default {
                    $Object = "{0} was {1} at {2}" -f $Event.SourceEventArgs.FullPath,
                    $Event.SourceEventArgs.ChangeType,
                    $Event.TimeGenerated
                }
            }
            $WriteHostParams = @{
                ForegroundColor = 'Green'
                BackgroundColor = 'Black'
                Object          = $Object
            }
#            Write-Verbose @WriteHostParams
        }
    }
    $ObjectEventParams = @{
        InputObject = $FileSystemWatcher
        Action      = $Action
    }

    ForEach ($Item in $EventName) {
        $ObjectEventParams.EventName = $Item
        $ObjectEventParams.SourceIdentifier = "File.$($Item).$($Path)"
        $Null = Register-ObjectEvent @ObjectEventParams
    }
    New-BurntToastNotification -Text "Registered FileSystemWatchers for $Path"
}

相关内容