等待Powershell中的特定事件

时间:2013-04-11 22:22:04

标签: security events powershell

我正在PowerShell中编写一个脚本,它将等待Windows 7中的特定事件。 安全日志中的事件ID 4776。当计算机被锁定时,脚本将运行。

该脚本应该在空闲时运行,基本上是一段时间(真实)循环,并且它将等待事件的“失败审计”发生。一旦事件发生,它将向计数器添加一个。一旦事件发生在“成功审核”状态,它将从循环中断,从而完成脚本。

我最初的想法是采取事件的日期并与运行时间比较,如果匹配,则等等。

到目前为止我所拥有的:

$i=0
while(true){       
   $date = Get-Date -format G
   $eventtime_fail=Get-EventLog Security | ? {$_.EventId -eq 4776} | where {$_.entrytype -eq "FailureAudit"} | Select-Object -expand TimeGenerated | Select -first 1
   $eventtime_success=Get-EventLog Security | ? {$_.EventId -eq 4776} | where {$_.entrytype -eq "SuccessAudit"} | Select-Object -expand TimeGenerated | Select -first 1

    if($date -eq $eventtime_fail){
         $i++
     }
    else if($date -eq $eventtime_success){
          break
     }
}

我意识到我可以简单地创建一个计划任务并完成它但我真的需要它是独立的。此脚本将在计算机锁定后运行,并在计算机解锁后停止执行。

在Windows XP中,有一种方法让脚本等待事件发生,然后运行某种指令,这就是我需要的,这就是所谓的eventtriggers.exe,它在vista发布时删除了计划任务取代了它,但是,通过powershell脚本,计划任务的工作方式不同。

除了我这样做之外,还有其他方法吗?有没有办法让eventtriggers.exe恢复或至少像这样的东西?帮助我StackOverflow的人,你唯一的希望。

2 个答案:

答案 0 :(得分:1)

我没有测试它,但imo应该工作。尝试创建一个事件日志监听器。

$seclog = Get-EventLog -List | Where-Object {$_.Log -eq 'Security'}
Register-ObjectEvent -InputObject $seclog -SourceIdentifier NewEventLogEntry -EventName EntryWritten -Action {

    $entry = $event.SourceEventArgs.Entry

    if($entry.EventID -eq 4776)
    {
        if($entry.EntryType -eq 'SuccessAudit')
        {
            'code for SuccessAudit'
        }
        elseif($entry.EntryType -eq 'FailureAudit')
        {
            'code for FailureAudit'
        }
    }
}

答案 1 :(得分:0)

您可以使用Microsoft documentation中描述的SytemEvents之一。

您将在Running a script before locking or after unlocking a computer (Windows 7/Vista/XP)中找到启动和停止脚本的方法。