ShadowM82
ShadowM82

Reputation: 113

Waiting for a specific event in Powershell

I am writing a script in powershell, that will wait for a specific event in Windows 7. Event ID 4776, in the Security Log. The script will run when the computer is locked.

The script is supposed to run in idle, essentially a while(true) loop, and it will wait for the "Failed Audit" of the event to occur. Once the event happens, it will add one to a counter. Once the event happens in a "Success Audit" status, it will break from the loop and thus be done with the script.

My initial idea, was to take the date of the event and compare to the date of running time and if it matches, then etc.

What I have so far:

$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
     }
}

I realize that i could just simply create a scheduled task and be done with it but I really need this to be standalone. This script will run once the computer locks, and stops execution once the computer is unlocked.

In Windows XP, there was a way for a script to wait for an event to occur and then run some sort of instruction, which is what I need, this was called eventtriggers.exe, it was removed when vista came out and scheduled tasks replaced it, however, scheduled tasks does not work the same way via powershell script.

Is there anyway to do this other than the way i am doing it? Is there a way to bring eventtriggers.exe back or at least something like it? Help me people of StackOverflow, your my only hope.

Upvotes: 1

Views: 5620

Answers (2)

Shay Levy
Shay Levy

Reputation: 126722

I didn't test it but imo should work. Try to create an eventlog listener.

$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'
        }
    }
}

Upvotes: 1

JPBlanc
JPBlanc

Reputation: 72610

You can use one of the SytemEvents discribed in Microsoft documentation.

You will find in Running a script before locking or after unlocking a computer (Windows 7/Vista/XP) a way to start and to stop your script.

Upvotes: 0

Related Questions