如何使用Powershell判断何时将一系列文件添加到网络

安迪

所以我有一个powershell脚本,主要是从这里的一个类似问题中提取的,可以检测到何时将某种类型的文件添加到某个网络并在发生这种情况时发送电子邮件:

Function Watcher{

param ($folder, $filter, $to, $Subject)



$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
    IncludeSubdirectories = $true
    EnableRaisingEvents = $true
}

$changeAction = [scriptblock]::Create('

        $path = $Event.SourceEventArgs.FullPath
        $name = $Event.SourceEventArgs.Name
        $changeType = $Event.SourceEventArgs.ChangeType
        $timeStamp = $Event.TimeGenerated
        Write-Host "The file $name was $changeType at $timeStamp"

        $Body = "The file $name was $changeType at $timeStamp"

        Email $to $Subject $Body

 ')

    Register-ObjectEvent $Watcher -EventName "Created" -Action $changeAction


}

但是,我想对此进行修改,以使其对本应用程序有用:现在有一个工具可以将数据(.datx文件)添加到网络(每分钟几个文件),并且我想在收到电子邮件通知的那一刻数据已完成记录。我如何最轻松地进行修改,以便在触发初始监视程序时,它等待是否再次发生,如果发生则重设,如果没有发生则重新设置?还是最好创建一个全新的脚本?基本上,我该如何使观察者被上载到网络的一个单独的.datx文件激活,但又不被它们的流触发(除了最后一个)

mklement0

您可以使用以下批处理方法:

  • 定义滑动时间窗口的长度,如果在其中创建了新文件,该时间窗口将重置;当事件到达该滑动窗口时,请继续收集事件。

    • 为防止集合无限期增长,请定义一个最大的批处理大小,即使要处理其他事件,也要处理该批处理。
  • 在没有新事件到达的时间窗口过去之后,处理手头的批次,即到目前为止收集的事件,然后开始新的批次。

  • 警告

    • System.IO.FileSystemWatcher班可报告重复的事件。

    • 下面的代码消除了给定批次中的重复项,但消除多个批次中的重复项,这将需要更多的精力-请参阅源代码注释。

  • 实施说明:

    • 而不是使用-Action传递脚本块Register-ObjectEvent来处理事件,而是循环中对它们进行同步处理(带有超时)Wait-Event

    • Wait-Event使用PowerShell的事件队列,因此通常不会错过事件(尽管在大容量情况下可能会在.NET级别发生);相反,如果方法等待时碰巧到达,则FileSystemWatcher类似的WaitForChanged方法不会事件排队,仅报告一个事件。

try {

  # Specify the target folder: the system's temp folder in this example.
  $dir = (Get-Item -EA Ignore temp:).FullName; if (-not $dir) { $dir = $env:TEMP }

  # Create and initialize the watcher.
  # Note the [ordered] to ensure that .EnableRaisingEvents is set last.
  $watcher = [System.IO.FileSystemWatcher] [ordered] @{
    Filter              = '*.datx'
    Path                = $dir
    EnableRaisingEvents = $true
  }

  # To simulate file creation, create *.datx files in the folder printed
  # mentioned in the following status message.
  Write-Host "Watching $dir for creation of $($watcher.Filter) files..."

  # Register for (subscribe to) creation events:
  # Determine a unique event-source ID...
  [string] $sourceId = New-Guid
  # ... and register for the watcher's Created event with it.
  Register-ObjectEvent $watcher -EventName Created -SourceIdentifier $sourceId

  # Initialize the ordered hashtable that collects all file names for a single 
  # batch.
  # Note: Since any given file creation can trigger *multiple* events, we 
  #       use an ordered hashtable (dictionary) to ensure that each file is 
  #       only reported once.
  #       However, *across batches* duplicates can still occur - see below.
  $batch = [ordered] @{}

  # Determine the sliding time window during which newly created files are 
  # considered part of a single batch.
  # That is, once a file has been created, each additional file created
  # within that time window relative to previous file becomes part of the
  # same batch.
  # When a time window elapses without a new file having been created, the
  # batch is considered complete and processed - see max. batch-size exception
  # below.
  # IMPORTANT:
  #  * The granularity is *seconds*, so the time window must be at least 1 sec.
  #  * Seemingly independently of the length of this window, duplicate events
  #    are likely to occur across batches the less time has elapsed between
  #    the end of a batch and the start of a new one - see below.
  $batchTimeWindowSecs = 5

  # How many names to allow a batch to contain at most, even if more
  # files keep getting created in the sliding time window.
  $maxBatchSize = 100

  while ($true) {
    # Run indefinitely; use Ctrl-C to exit.

    # Wait for events in a sliding time window of $batchTimeWindowSecs length.
    # Note: Using Wait-Event in a loop (1 event per iteration) is *more* 
    #       predictable than the multi-event collecting Get-Event in terms of
    #       avoiding duplicates, but duplicates do still occur.
    $batch.Clear()
    while ($evt = Wait-Event -SourceIdentifier $sourceId -Timeout $batchTimeWindowSecs) {
      $evt | Remove-Event  # By default, events linger in the queue; they must be removed manually.
      # Add the new file's name to the batch (unless already present)
      # IMPORTANT:
      #  * Duplicates can occur both in a single batch and across batches.
      #  * To truly weed out all duplicates, you'd have to create a session-level
      #    dictionary of the files' names and their creation timestamps.
      #    With high-volume file creation, this session-level dictionary could
      #    grow large; periodic removal of obsolete entries would help.
      $batch[$evt.SourceArgs.Name] = $null # dummy value; it is the *keys* that matter.
      Write-Host ✔ -NoNewline # status output: signal that a new file was created
      # If the max. batch size has been reached, submit the batch now, even if further
      # events are pending within the timeout window.
      if ($batch.Count -ge $maxBatchSize) { 
        Write-Warning "Max. batch size of $maxBatchSize reached; force-submitting batch."
        break
      }
    }

    # Completed batch available?
    if ($batch.Count) {      
      # Simulate processing the batch.
      Write-Host "`nBatch complete: Sending email for the following $($batch.Count) files:`n$($batch.Keys -join "`n")"                                            #`
      # Start a new batch.
      $batch.Clear()
    }
    else {
      Write-Host . -NoNewline # status output: signal that no new files were created in the most recent time window.
    }

  }

}
finally {
  # Clean up:
  # Unregister the event subscription.
  Unregister-Event -SourceIdentifier $sourceId
  # Dispose of the watcher.
  $watcher.Dispose() 
}

首先创建一批3个文件,然后再创建5个文件的示例输出:

Watching C:\Users\jdoe\AppData\Local\Temp for creation of *.datx files...
............✔✔✔
Batch complete: Sending email for the following 3 files:
1.datx
2.datx
3.datx
.✔✔✔✔✔
Batch complete: Sending email for the following 5 files:
4.datx
5.datx
6.datx
7.datx
8.datx
....................

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

将一系列 HKWorkouts 添加到 UserDefaults

来自分类Dev

如何将列表中的标题添加到一系列直方图?

来自分类Dev

如何将具有递减值的多行添加到一系列中

来自分类Dev

如何将列表中的标题添加到一系列直方图?

来自分类Dev

如何非常快速地将数字添加到向量中的一系列元素

来自分类Dev

将超棒字体图标添加到一系列按钮

来自分类Dev

将中心线添加到一系列.jpg图像中

来自分类Dev

将随机天数添加到一系列日期时间值中

来自分类Dev

将数据验证(下拉)列表添加到一系列单元格?

来自分类Dev

为变量的每个值将一系列值添加到另一个变量

来自分类Dev

如何使用Javascript或Jquery将一系列JSON数据附加到HTML?

来自分类Dev

将基于新数据的折线图添加到一系列箱形图

来自分类Dev

将一系列艺术家添加到 1 个音乐节不起作用

来自分类Dev

如何将在数据库中找到的值添加到一系列下拉按钮?

来自分类Dev

如何使用Bash遍历一系列文件

来自分类Dev

使用KVO判断何时将元素添加到数组

来自分类Dev

需要从一系列值中添加到一些列表元素

来自分类Dev

当列为一系列列表时,如何有条件地将其添加到pandas dataframe列中的单元格选择中?

来自分类Dev

使用Powershell读取文本文件中的一系列字符吗?

来自分类Dev

用 C 将一系列数字写入文件

来自分类Dev

如何添加一系列数字中的Java

来自分类Dev

如何在python中添加一系列数字

来自分类Dev

如何从网站下载一系列文件?wget?

来自分类Dev

如何从Python文件中解脱一系列对象?

来自分类Dev

如何批量解密一系列PDF文件?

来自分类Dev

如何处理一系列配对文件

来自分类Dev

如何从网站下载一系列文件?wget?

来自分类Dev

如何将Django的APIRequestFactory与一系列对象一起使用?

来自分类Dev

如何将OFFSET()公式与一系列值一起使用?

Related 相关文章

  1. 1

    将一系列 HKWorkouts 添加到 UserDefaults

  2. 2

    如何将列表中的标题添加到一系列直方图?

  3. 3

    如何将具有递减值的多行添加到一系列中

  4. 4

    如何将列表中的标题添加到一系列直方图?

  5. 5

    如何非常快速地将数字添加到向量中的一系列元素

  6. 6

    将超棒字体图标添加到一系列按钮

  7. 7

    将中心线添加到一系列.jpg图像中

  8. 8

    将随机天数添加到一系列日期时间值中

  9. 9

    将数据验证(下拉)列表添加到一系列单元格?

  10. 10

    为变量的每个值将一系列值添加到另一个变量

  11. 11

    如何使用Javascript或Jquery将一系列JSON数据附加到HTML?

  12. 12

    将基于新数据的折线图添加到一系列箱形图

  13. 13

    将一系列艺术家添加到 1 个音乐节不起作用

  14. 14

    如何将在数据库中找到的值添加到一系列下拉按钮?

  15. 15

    如何使用Bash遍历一系列文件

  16. 16

    使用KVO判断何时将元素添加到数组

  17. 17

    需要从一系列值中添加到一些列表元素

  18. 18

    当列为一系列列表时,如何有条件地将其添加到pandas dataframe列中的单元格选择中?

  19. 19

    使用Powershell读取文本文件中的一系列字符吗?

  20. 20

    用 C 将一系列数字写入文件

  21. 21

    如何添加一系列数字中的Java

  22. 22

    如何在python中添加一系列数字

  23. 23

    如何从网站下载一系列文件?wget?

  24. 24

    如何从Python文件中解脱一系列对象?

  25. 25

    如何批量解密一系列PDF文件?

  26. 26

    如何处理一系列配对文件

  27. 27

    如何从网站下载一系列文件?wget?

  28. 28

    如何将Django的APIRequestFactory与一系列对象一起使用?

  29. 29

    如何将OFFSET()公式与一系列值一起使用?

热门标签

归档