Powershell IO.FileSystemWatcher - 文件夹最近 30 分钟未更新

Powershell IO.FileSystemWatcher - folder not updated for last 30 mins

我在 Powershell 脚本中寻求帮助。

如果目录日志位置 C:\Users146187\Downloads\Syslogd 在过去 30 分钟内没有创建或更改任何新文件,我想 运行 函数“RunMyStuff”。我也没有注销功能。不确定,我应该把它放在哪里。谢谢

Function RunMyStuff {
        # this is the bit I want to happen when there is no file created for 30 mins under C:\Users146187\Downloads\Syslogd
     Start-Process 'C:\windows\system32\calc.exe'
     Write-Host $global:FileCreated
    }
    
    Function Watch {    
        $global:FileCreated = $false 
        $folder = "C:\Users146187\Downloads\Syslogd"
        $filter = "*.*"
        $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
            IncludeSubdirectories = $false 
            EnableRaisingEvents = $true
        }
    
        Register-ObjectEvent $Watcher "Created" -Action {$global:FileCreated = $true} > $null
         
        Start-Sleep -Seconds 120
        
        while($true){
            while ($global:FileCreated -eq $true){
                 Start-Sleep -Seconds 600
                 Write-Host $global:FileCreated
            }
           
            RunMyStuff
            
            $global:FileCreated = $false
        }
    }
    
    Watch

这可能是您要查找的示例。它使用带有 FileWatcher 事件的 Timer 事件。

function RunMyStuff()
{
    Write-Host "$(get-date) RunMyStuff (no files added within last 10 seconds)"
    # Start-Process "calc.exe"
}

function Watch ($folder) {
    Write-Host "Watching $((Get-Item $folder).Fullname)"
    $global:FileCreated = $true

    $filter = "*.*"
    $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
        IncludeSubdirectories = $false
        EnableRaisingEvents = $true
    }
    Register-ObjectEvent -InputObject $watcher -EventName "Created" -SourceIdentifier "myFileWatcher" -Action { 
        $global:timer.Stop()
        $global:FileCreated = $true
        $global:timer.Start()
    } > $null

    $global:timer = New-Object Timers.Timer
    $global:timer.Interval = 10000
    Register-ObjectEvent -InputObject $global:timer -EventName "Elapsed" -SourceIdentifier "myTimer" -Action {
        $global:FileCreated = $false
    } > $null

    $global:timer.Start()

    try {
        while ($true) {
            Start-Sleep -Seconds 1
            if (!$global:FileCreated) {
                RunMyStuff
                $global:FileCreated = $true
            }
        }
    }
    finally {
        Unregister-Event -SourceIdentifier "myFileWatcher"
        Unregister-Event -SourceIdentifier "myTimer"
    }
}

Watch "C:\"

这是实际操作: