Home > Mobile >  Extract Username From Log Text using Powershell
Extract Username From Log Text using Powershell

Time:09-17

I'm trying to extract all usernames that has failed login atempts from Event Viewer log and then list only the usernames. However the data for each entry is text so I have a hard time extracting only the names (Intruder123 in this case). It would be a couple of hundred account names stored in an array.

$String = Get-WinEvent @{LogName='Security';ProviderName='Microsoft-Windows-Security-Auditing';ID=4625 }  -ComputerName SECRETSERVER |
    Select-Object -ExpandProperty Message

$string -match "Account Name:       (?<content>.*)"
$matches['content']

The data looks like this (multiple times):

Account For Which Logon Failed:
    Security ID:        S-1-0-0
    Account Name:       Intruder123
    Account Domain:     SECRET.LOCAL

CodePudding user response:

I think you could collect some more information like the time the failed logon happened and on which computer. For that, create a resulting array of objects.
Also, trying to parse the Message property can be cumbersome and I think it is much better to get the info from the Event as XML:

$filter = @{LogName='Security';ProviderName='Microsoft-Windows-Security-Auditing';ID=4625 }
$result = Get-WinEvent -FilterHashtable $filter -ComputerName SECRETSERVER | ForEach-Object {
    # convert the event to XML and grab the Event node
    $eventXml = ([xml]$_.ToXml()).Event
    $userName = ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'
    $computer = ($eventXml.EventData.Data | Where-Object { $_.Name -eq 'WorkstationName' }).'#text'
    # output the properties you need
    [PSCustomObject]@{
        Time     = [DateTime]$eventXml.System.TimeCreated.SystemTime
        UserName = $userName
        Computer = $computer
    }
}

# output on screen
$result

# output to CSV file
$result | Export-Csv -Path 'X:\FailedLogons.csv' -NoTypeInformation
  • Related