0

我有一个通过 Windows 计划任务调用的脚本,该任务是基于某个 Windows 应用程序事件触发的。但是,如果事件在 1 分钟内发生 3 次或更多次,则执行脚本才是关键;如果事件每分钟发生一次,则不应采取任何措施。

我知道这可以在脚本本身中处理。假设我需要至少 2 个新变量:

# time window, in seconds
$maxTime = 60

# max number of times this script needs to be called, within $maxTime window, 
# before executing the rest of the script
$maxCount = 3  

我开始概述使用临时文件作为跟踪的算法,但认为可能会有一个更简单的解决方案,有人可以向我展示。谢谢

4

2 回答 2

1

您可以将执行时间存储在环境变量中。

在此脚本生效之前,您必须创建 LastExecutionTimes 环境变量。

$maxTime = 60
$maxCount = 3
$now = Get-Date

# Get execution times within the time limit.
$times = @($env:LastExecutionTimes -split ';'| 
            Where-Object {$_ -and $now.AddSeconds(-1 * $maxTime) -lt $_})

$times += '{0:yyyy-MM-dd HH:mm:ss}' -f $now
$env:LastExecutionTimes = $times -join ';'

if($times.Length -lt $maxCount) {return}

# Reset the execution times
$env:LastExecutionTimes =''

Write-Host 'Continue Script' -ForegroundColor Yellow
于 2013-04-26T14:39:18.620 回答
0

我会编写一个文本文件和一个辅助脚本或函数来检查它。本质上它每次都会调用它,然后在调用时将信息写入文本文件。

像这样的东西:

if(!((Get-Date).AddMinutes(-1) -lt $oldTime))
 {
    $CurDate = Get-Date
    "$CurDate, 1" | out-File "TheCheck.txt"
 }
 else 
 {
  $counter++
  if($counter -ge 3) {Call WorkerFunction}
   else{
    "$oldTime, $counter" | Out-File "TheCheck.txt"
 }

它缺少一些变量,但总体上应该可以作为补充脚本使用。然后你的计划任务实际做的是调用它,如果自 1 分钟以来的时间$oldTime超过 1 分钟,那么它会用当前时间和 1 为$counter变量重写文件。如果距离第一次调用它不到一分钟,则检查它$counter,如果它是 3 或更高(也可以-eq)到 3,那么它会调用你的主脚本。

于 2013-04-26T01:40:38.533 回答