Powershell: Audit Logon and Logoff times from the event log

The below PowerShell script queries a remote computers event log to retrieve the event log id’s relating to Logon 7001 and Logoff 7002. Creating a nice little audit of when the computer was logged on and off.

Prerequisites

The remote computer will need to be online and the “Remote Registry” service needs to be started, this can be done remotely using service.msc and selecting “Connect to another computer” in the actions menu.

remote_registry



The Script

At the very bottom of the script you will need to change the computer name and you can change the number of days if required.

function get-logonhistory {
    Param (
        [string]$Computer = (Read-Host Remote computer name),
        [int]$Days = 10
    )
    cls
    $Result = @()
    Write-Host "Gathering Event Logs, this can take awhile..."
    $ELogs = Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-$Days) -ComputerName $Computer
    If ($ELogs) {
        Write-Host "Processing..."
        ForEach ($Log in $ELogs) {
            If ($Log.InstanceId -eq 7001) {
                $ET = "Logon"
            }
            ElseIf ($Log.InstanceId -eq 7002) {
                $ET = "Logoff"
            }
            Else {
                Continue
            }
            $Result += New-Object PSObject -Property @{
                Time         = $Log.TimeWritten
                'Event Type' = $ET
                User         = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])
            }
        }
        $Result | Select Time, "Event Type", User | Sort Time -Descending | Format-Table

        Write-Host "Done."
    }
    Else {
        Write-Host "Problem with $Computer."
        Write-Host "If you see a 'Network Path not found' error, try starting the Remote Registry service on that computer."
        Write-Host "Or there are no logon/logoff events (XP requires auditing be turned on)"
    }
}


get-logonhistory -Computer "COMPUTERNAME" -Days "7"

The script was origionally posted by Martin Pugh over at SpiceWorks, I also found the Power Shell script over on the TechNet site.

1 thought on “Powershell: Audit Logon and Logoff times from the event log”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.