You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:PowerShell监控文件变更脚本重复执行两次问题

文件变更触发两次执行的问题排查与解决

问题原因

System.IO.FileSystemWatcher的Changed事件本身容易触发多次,这是因为多数程序修改文件时会分多步操作(比如写入内容后更新文件元数据、或是先写入临时文件再替换原文件),每一步操作都会单独触发一次变更事件,导致你的脚本连续执行两次程序。

解决方案

以下是两种可行的解决方法,其中时间过滤法是最稳妥的通用方案:

方案1:通过时间间隔过滤重复事件

在脚本中记录上次触发事件的时间,仅当当前事件与上次事件间隔超过设定阈值(比如500毫秒)时,才执行目标程序,以此避免短时间内的重复触发。

修改后的完整脚本:

$folderToWatch = "C:\Users\user\FTP"
$fileToWatch = "file.txt"  

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $folderToWatch
$watcher.Filter = $fileToWatch
$watcher.EnableRaisingEvents = $true

# 存储上次触发事件的时间,初始设为最小时间值
$lastTriggerTime = [DateTime]::MinValue

$action = {
    $executablePath = "C:\DotNet\Program.exe"
    $filePath = $Event.SourceEventArgs.FullPath
    $currentTime = Get-Date
    
    # 仅处理间隔超过500ms的事件
    if (($currentTime - $script:lastTriggerTime).TotalMilliseconds -gt 500) {
        Write-Host "New or modified file detected: $filePath"
        Write-Host "Executable path: $executablePath"
        try {
            Start-Process -FilePath $executablePath -Wait
        } catch {
            Write-Host "Error starting the process: $_"
        }
        # 更新上次触发时间
        $script:lastTriggerTime = $currentTime
    }
}

Register-ObjectEvent -InputObject $watcher -EventName Changed -Action $action

方案2:仅处理特定类型的变更事件

通过判断事件的ChangeType属性,只响应文件内容变更的事件,过滤掉属性变更等触发的冗余事件。不过这种方法无法覆盖所有重复触发场景,建议作为时间过滤法的补充使用。

示例判断逻辑:

if ($Event.SourceEventArgs.ChangeType -eq [System.IO.WatcherChangeTypes]::Changed) {
    # 执行目标程序的逻辑
}

内容的提问来源于stack exchange,提问作者nnchvxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 11:26:19