使用 Powershell 从日志文本中提取用户名

Extract Username From Log Text using Powershell

我试图从事件查看器日志中提取所有登录尝试失败的用户名,然后仅列出用户名。然而,每个条目的数据都是文本,所以我很难只提取名称(在本例中为 Intruder123)。这将是存储在数组中的数百个帐户名。

$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']

数据看起来像这样(多次):

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

我认为您可以收集更多信息,例如登录失败发生的时间和发生在哪台计算机上。为此,创建一个结果对象数组。
此外,尝试解析消息 属性 可能很麻烦,我认为从事件中获取信息要好得多 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