如果PowerShell脚本在1分钟内被调用了3次,您如何继续执行它?
我有一个通过Windows计划任务调用的脚本,该任务是根据某个Windows应用程序事件触发的。但是,如果事件在1分钟内发生3次或更多次,则执行脚本才是关键;如果事件每分钟发生一次,则不应采取任何行动 我知道这可以在脚本中处理。假设我至少需要两个新变量:如果PowerShell脚本在1分钟内被调用了3次,您如何继续执行它?,powershell,powershell-1.0,Powershell,Powershell 1.0,我有一个通过Windows计划任务调用的脚本,该任务是根据某个Windows应用程序事件触发的。但是,如果事件在1分钟内发生3次或更多次,则执行脚本才是关键;如果事件每分钟发生一次,则不应采取任何行动 我知道这可以在脚本中处理。假设我至少需要两个新变量: # time window, in seconds $maxTime = 60 # max number of times this script needs to be called, within $maxTime window, #
# 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
我开始用一个临时文件来描述一个算法,但是我认为可能有一个更简单的解决方案可以给我看。谢谢我会写一个文本文件和一个辅助脚本或函数来检查它。实际上,它每次都会调用它,然后在调用时将信息写入文本文件 下面的例子是:
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"
}
它缺少一些变量,但总体上应该作为补充脚本。然后,计划的任务实际执行的是调用此函数,如果自
$oldTime
以来的时间超过1分钟,则它将使用当前时间覆盖文件,并为$counter
变量覆盖1。如果第一次调用后不到一分钟,它将检查$计数器
,如果它是3或更高(也可以执行-eq
)到3,则它将调用主脚本。您可以将执行时间存储在环境变量中
$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
在该脚本开始工作之前,必须创建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
3或更高版本的检查应该是
$counter-ge 3
,并且$counter
应该在检查之前增加,因为存在导致脚本运行的新事件。即使这样,只存储一次也不行。如果每40秒间隔3个事件,计数器将增加到3,但从第一个事件到第三个事件的时间将为1分20秒。仅供参考,我在保存环境变量并将其转入下一次调用脚本时遇到问题(新的powershell实例)。因此,我更新了脚本以使用另一种get/set方法:$envTimes=[Environment]::GetEnvironmentVariable(“LastExecutionTimes”,“User”)
和[Environment]::SetEnvironmentVariable(“LastExecutionTimes”),“$envTimes”,“User”)
这样做有效,而且不需要事先添加变量。