Public/Get-specLastLogonEvent.ps1
function Get-specLastLogonEvent { <# .SYNOPSIS Retrieves the most recent logon event from the Security log for a specified domain. .DESCRIPTION This function queries the Windows Security event log for the most recent logon event (Event ID 4624). If no domain is specified, it defaults to 'specsavers.com'. .PARAMETER DomainName Specifies the domain name to filter logon events. Defaults to 'specsavers.com'. .EXAMPLE Get-specLastLogonEvent -DomainName "specsavers.com" Retrieves the most recent logon event for any user in the "specsavers.com" domain. .EXAMPLE Get-specLastLogonEvent Retrieves the most recent logon event for any user, using the default domain of 'specsavers.com'. .NOTES Author: owen.heaume Version: 1.0 #> [CmdletBinding()] param ( [string]$DomainName = 'specsavers.com' ) # Define the filter hashtable for Event ID 4624 $filterHashTable = @{ LogName = 'Security' Id = 4624 } # Get logon events using the filter hashtable $lastLogonEvent = Get-WinEvent -FilterHashtable $filterHashTable | Where-Object { $_.Properties[5].Value -like "*@$DomainName" } | Select-Object -First 1 -Property TimeCreated, Properties if ($lastLogonEvent) { $lastLogonTime = $lastLogonEvent.TimeCreated $username = $lastLogonEvent.Properties[5].Value $domain = $lastLogonEvent.Properties[6].Value [PSCustomObject]@{ 'LastLogonTime' = $lastLogonTime 'Username' = $username 'Domain' = $domain } } else { Write-Output 'No logon event found for the specified domain.' } } |