Tuesday, October 31, 2017

Create Logon Event in Event Log

SCENARIO

You don't like how the Windows Security Log records logon events. You want to create your own logon events and record information that you find useful.


SCRIPT

This Powershell script will write an event 3001 to the Application event log whenever it is run. In order to get logon information, we use this script as a logon script. The result in the event log looks something like this:


Keep in mind that the script just writes this information so you must have it run at logon via GPO or scheduled task or something like that.


<#
    Write Logon data to local application event log.
#>
# Variables
    $TimeStamp = Get-Date
    $date = Get-Date -Format d
    $dayofweek = $TimeStamp.DayOfWeek
    $time = Get-Date -Format T
# Check to see if Source Exists
    $SourceExists = [system.diagnostics.eventlog]::SourceExists(“LogonInfo”)
# If source does not exist, create LogonInfo Source
    If ($SourceExists -ne "True") {New-EventLog -LogName Application -Source “LogonInfo”}
# Write to Event Log
    Write-EventLog -LogName "Application" -Source "LogonInfo" -EventID 3001 -EntryType Information `
    -Message "Below is information pertaining to a user logon event.
   
    User: $env:username
    User Domain: $env:USERDNSDOMAIN
    Computer: $env:COMPUTERNAME
    Day of the Week: $dayofweek
    Date: $date
    Time: $time
   
    " -Category 1 -RawData 10,20


You can save the file and then set it as a logon script via GPO.


NOTE: If the script writes two events back to back then you probably have loopback policies in place. Since this was my situation, I created a separate GPO and applied it to the OU containing the computers I wanted to write these events to. After doing that, it worked fine.

NOTE: The cmdlet only works when the user is an administrator on the computer. So if you run this as a logon script and the users logging into the computer are administrators to the computer, then you are set.

RESOURCES

https://blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/how-to-use-powershell-to-write-to-event-logs/
https://ss64.com/ps/write-eventlog.html
http://jeffmurr.com/blog/?p=231

No comments:

Post a Comment