FileWatcher任务

时间:2014-03-07 19:50:25

标签: powershell filesystemwatcher

目标:创建一个文件观察程序,以便在文件停止写入时执行某些任务(即文件大小停止更改或上次写入没有在X时间内发生)

我知道您可以在创建/删除/更改/重命名文件时使用powershell创建任务。如果文件在X时间内没有改变(使用powershell或其他语言),有没有办法利用这个来说做某事?

    $folder = '<path>' # Enter the root path you want to monitor. 
    $filter = '*.*'  # You can enter a wildcard filter here. 

    # In the following line, you can change 'IncludeSubdirectories to $true if required.                           
    $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 

    # Here, all three events are registerd.  You need only subscribe to events that you need: 

    Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
    $name = $Event.SourceEventArgs.Name 
    $changeType = $Event.SourceEventArgs.ChangeType 
    $timeStamp = $Event.TimeGenerated 
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green 
    Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} 

    Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action { 
    $name = $Event.SourceEventArgs.Name 
    $changeType = $Event.SourceEventArgs.ChangeType 
    $timeStamp = $Event.TimeGenerated 
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore red 
    Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} 

    Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action { 
    $name = $Event.SourceEventArgs.Name 
    $changeType = $Event.SourceEventArgs.ChangeType 
    $timeStamp = $Event.TimeGenerated 
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore white 
    Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} 

    # To stop the monitoring, run the following commands: 
    # Unregister-Event FileDeleted 
    # Unregister-Event FileCreated 
    # Unregister-Event FileChanged

2 个答案:

答案 0 :(得分:0)

我不知道您可以用来触发的事件类型,但您可以在更改或创建时启动这样的流程:

while ($true)
 {
   try{ 
        [IO.file]::openwrite(<filepath>).close()
        break
      }

   catch { start-sleep -Seconds 5 }
 }

 do-stuff

只要文件被写入您就无法获得写锁定,并且openwrite将抛出错误。一旦关闭,openwrite就会成功,打破循环并进入脚本的其余部分。

答案 1 :(得分:0)

当您在指定的时间段内检查没有事件时,等待事件将无法帮助您。您可以检查LastWriteTime属性以查看文件是否在给定的时间范围内更改:

$threshold = 5  # minutes

$f = Get-Item 'C:\path\to\your.file'

if (((Get-Date) - $f.LastWriteTime).TotalMinutes -lt $threshold) {
  'File has been changed.'
}