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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用FileSystemWatcher警告多个文件是否同时更改相关的知识,希望对你有一定的参考价值。

我对powershell很新。以下代码由BigTeddy创建,他获得了全部功劳(我还使用While循环进行了一些更改)

我想知道如何创建if / else语句,以便如果同时更改/编辑/创建/删除多个文件(比如同时编辑了10个文件),将创建一个日志文件,说明这些列表文件已在此特定时间同时编辑。

以下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.
答案

您是否考虑过将时间戳和操作(创建/修改/删除)作为键和文件名作为值的哈希表。您在特定等待间隔后迭代字典,并将字典中的条目刷新到日志文件。

以上是关于使用FileSystemWatcher警告多个文件是否同时更改的主要内容,如果未能解决你的问题,请参考以下文章

C#:FileSystemWatcher - 多个监视文件夹问题

C# FileSystemWatcher - 多个事件

创建同一个 FileSystemWatcher 的多个实例

文件夹上的 Filesystemwatcher 并获取文件名

FileSystemWatcher:将多个过滤器事件聚合成一个?

c# 中的FileSystemWatcher问题