我有以下脚本:
$pattern = 'Unable to authenticate user!'
$events = Get-WinEvent -ea SilentlyContinue `
-ProviderName "Windows DB Controller - Task Manager Service"|
Where-Object { $_.TimeCreated -gt [datetime]::today -and $_.Message -match $pattern }
$events >> D:Error.txt
if ($events) {
Send-MailMessage -SmtpServer smtp.domain.com -From No-reply@domain.com -To sunny@domain.com -Subject 'Error found in log' -Body $events
}
我已安排它每 10 分钟运行一次,并且故意,我想使用上面的脚本实现以下几点:
Search the specified error message in the event viewer log only for current-date and as soon as the error message encountered send a email notification to me but didn't want to receive email notification for the error message which appreared today and for which I had already been notified (I mean , wanted to receive error-notification only once for a specific time of current day).
但是我在这里面临的问题是:为已经通知的同一错误消息获取多个通知。
我希望我足够清楚,可以提出我的确切问题。
你能帮帮我吗,如何解决这个问题?
如果您每 10 分钟运行一次脚本,我会更改 Where-Object 上的条件,而不是获取"今天"的所有事件;我会更改它以仅获取过去 10 分钟内发生的事件。即代码变为:
Where-Object { $_.TimeCreated -gt [datetime]::now.AddMinutes(-10) -and $_.Message -match $pattern }
看看这个线程:
Powershell - Tail Windows Event Log?可能吗?
它是在跟踪事件日志上,但相同的方法应该适用于您要做的事情。 只需在运行之间将最后一个索引号保存到文件中即可。
以下方法怎么样:
Register-WmiEvent -Query "select * from __InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent' and TargetInstance.SourceName = 'Windows DB Controller - Task Manager Service' and TargetInstance.Message LIKE '%Unable to authenticate user!%'" -SourceIdentifier "MyEventListener" -Action {
#Your actions
write-host "$($eventargs.NewEvent.TargetInstance.RecordNumber) at $($eventargs.NewEvent.TargetInstance.TimeGenerated)"
}
它使用 WMI 订阅使用条件生成事件日志条目时发生的事件。操作本身将仅返回新对象(因此不再重复)。我提供了一个示例操作来帮助您了解如何访问该对象。此方法将为您提供实时监视。
在操作中,$eventargs.NewEvent.TargetInstance
将为您提供作为win32_ntlogevent
实例的对象。若要查看此类的属性,请查看 TechNet 或运行以下命令:
([wmiclass]'win32_ntlogevent').Properties | ft Name
要使脚本永久运行,只需使用 powershell -file script.ps1 -noexit
调用脚本或在脚本末尾包含一个 while($true)
循环。(我不确定 while-loop 将如何影响资源使用的长期,您必须进行测试)。