使用FileSystemWatcher来警告同时更改多个文件

6
我对powershell非常陌生。以下代码是由BigTeddy创建的,他得到了全部的功劳(我也使用While Loop进行了一些更改)。
我想知道如何创建一个if/else语句,以便在同时更改/编辑/创建/删除多个文件时(例如,同时编辑了十个文件),会创建一个日志文件,说明这些文件已经在特定时间同时被编辑。
以下powershell脚本是由BigTeddy创建的,基本上会输出一个日志文件(以及在powershell ISE的输出中),记录更改/编辑/创建/删除的时间以及被编辑的文件。
 param(
        [string]$folderToWatch = "C:\Users\gordon\Desktop\powershellStart"
      , [string]$filter        = "*.*"
      , [string]$logFile       = 'C:\Users\gordon\Desktop\powershellDest\filewatcher.log'
    )

    # In the following line, you can change 'IncludeSubdirectories to $true if required.
    $fsw = New-Object IO.FileSystemWatcher $folderToWatch, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
    $timeStamp           #My changes
    $timeStampPrev = $timeStamp         #My changes
# This script block is used/called by all 3 events and:
# appends the event to a log file, as well as reporting the event back to the console
$scriptBlock = {

  # REPLACE THIS SECTION WITH YOUR PROCESSING CODE
  $logFile = $event.MessageData # message data is how we pass in an argument to the event script block
  $name = $Event.SourceEventArgs.Name
  $changeType = $Event.SourceEventArgs.ChangeType
  $timeStamp = $Event.TimeGenerated
  while($timeStampPrev -eq $timeStamp) {     #My changes
  Write-Host "$timeStamp|$changeType|'$name'" -fore green
  Out-File -FilePath $logFile -Append -InputObject "$timeStamp|$changeType|'$name'"
  # REPLACE THIS SECTION WITH YOUR PROCESSING CODE
}
}


# Here, all three events are registered.  You need only subscribe to events that you need:
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -MessageData $logFile -Action $scriptBlock
Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -MessageData $logFile -Action $scriptBlock
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -MessageData $logFile -Action $scriptBlock

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


#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s).
#The advantage of this method over using WMI eventing is that this can monitor sub-folders.
#The -Action parameter can contain any valid Powershell commands.
#The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true.
#You need not subscribe to all three types of event.  All three are shown for example.

1
当10个文件同时被更改时,您将收到10个通知。如何处理它们由您决定。 - montonero
1
在同一分钟内,10秒内,1秒内,100毫秒内,10毫秒内等时间内编辑的文件是否算作“同时”? - Chris Magnuson
请立即返回翻译文本,谢谢。 - gordon sung
1个回答

3
你考虑过使用带有时间戳和操作(创建/修改/删除)作为键,文件名作为值的哈希表吗?在特定等待间隔之后,你可以遍历字典并将条目刷新到日志文件中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接