From 06b66813cf019127c2065c4df95835bc933cb82d Mon Sep 17 00:00:00 2001 From: ek-dyoder Date: Tue, 7 Jul 2026 15:06:27 -0400 Subject: [PATCH] fix: check both target and subject fields, 4624 type 7 is now an unlock event, 4634 now allows type 7 for logoff/session change, added security log access check --- Get-UserLogonActivity.ps1 | 50 +++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/Get-UserLogonActivity.ps1 b/Get-UserLogonActivity.ps1 index e30fbd2..0331b36 100644 --- a/Get-UserLogonActivity.ps1 +++ b/Get-UserLogonActivity.ps1 @@ -100,6 +100,25 @@ Function Get-EventDataValue { Return [string]$Data.'#text' } +Function Get-EventDataValueFromList { + Param( + [Parameter(Mandatory=$true)] + [xml]$EventXml, + + [Parameter(Mandatory=$true)] + [string[]]$Names + ) + + ForEach ($Name in $Names) { + $Value = Get-EventDataValue -EventXml $EventXml -Name $Name + If (-not [string]::IsNullOrWhiteSpace($Value) -and $Value -ne '-') { + Return $Value + } + } + + Return $null +} + Function Test-UserLogonActivityUser { Param( [AllowNull()] @@ -131,6 +150,16 @@ Function Format-UserName { Return "${DomainName}\${UserName}" } +Function Get-UserLogonActivitySecurityLogAccessError { + Try { + Get-WinEvent -ListLog Security -ErrorAction Stop | Out-Null + Return $null + } + Catch { + Return "Unable to read the Windows Security event log. Run PowerShell as administrator if access is denied. $($_.Exception.Message)" + } +} + Function ConvertTo-UserLogonActivity { Param( [Parameter(Mandatory=$true)] @@ -138,18 +167,23 @@ Function ConvertTo-UserLogonActivity { ) $EventXml = [xml]$Event.ToXml() - $UserName = Get-EventDataValue -EventXml $EventXml -Name 'TargetUserName' - $DomainName = Get-EventDataValue -EventXml $EventXml -Name 'TargetDomainName' + $UserName = Get-EventDataValueFromList -EventXml $EventXml -Names @('TargetUserName', 'SubjectUserName') + $DomainName = Get-EventDataValueFromList -EventXml $EventXml -Names @('TargetDomainName', 'SubjectDomainName') $LogonType = Get-EventDataValue -EventXml $EventXml -Name 'LogonType' $Activity = $null Switch ($Event.Id) { 4624 { - If ($LogonType -notin @('2', '10', '11')) { Return $null } - $Activity = 'logon' + Switch ($LogonType) { + '2' { $Activity = 'logon' } + '7' { $Activity = 'unlock' } + '10' { $Activity = 'logon' } + '11' { $Activity = 'logon' } + Default { Return $null } + } } 4634 { - If ($LogonType -notin @('2', '10', '11')) { Return $null } + If ($LogonType -notin @('2', '7', '10', '11')) { Return $null } $Activity = 'logoff' } 4647 { @@ -178,6 +212,12 @@ Function ConvertTo-UserLogonActivity { } } +$SecurityLogAccessError = Get-UserLogonActivitySecurityLogAccessError +If (-not [string]::IsNullOrWhiteSpace($SecurityLogAccessError)) { + Write-Error $SecurityLogAccessError + Exit 1 +} + $Filter = @{ LogName = 'Security' Id = @(4624, 4634, 4647, 4800, 4801)