Log filtering to txt

I’m novice to powershell. I want a script to write to a txt file when log 4720 is generated the following information: date and time of event ID, Subject: Account Name, New Account: Account Name.
I succeeded to extract only the date and time.

Get-EventLog -Log Security -Newest 30 | Where-Object { $_.EventID -eq 4720 } | Select-Object -Property TimeGenerated

Thanks in advance!


welcome to the forums

First of all - when you post code, error messages, sample data or console output format it as code, please.

Here you can read how that works: Guide to Posting Code.

Now to your challenge … unfortunately the information you’re after are hidden in the “Message” property of the returned object. So you have to do some regex acrobatics to cut them out of the rest of the message body.

Try the following snippet:

$FilterHashTable = @{
    LogName = 'Security'
    ID      = 4720
Get-WinEvent -FilterHashtable $FilterHashTable -ComputerName 'TargetedDC' -MaxEvents 30 |
ForEach-Object {
    $_.Message -match '(?smi)Account Name:\s*(\S*)\s*[\d\D]*Account Name:\s*(\S*)\s*'
        TimeCreated        = $_.TimeCreated
        SubjectAccountName = $Matches[1]
        NewAccountName     = $Matches[2]

Of course you should replace the value ‘TargetedDC’ with the name of the DC you want to query. :wink:

1 Like

Thank you very much, it worked for the first time!

Another way to do this would be to parse the XML:

$filterHashtable = @{

    LogName = 'Security'
    ID = 4720


$events = Get-WinEvent -FilterHashtable $filterHashtable

foreach ($event in $events) {

    $h = @{}
    [xml]$xEvent = $event.toXML()
    $xEvent.Event.EventData.Data | ForEach-Object {


        [PSCustomObject] @{

            TimeCreated = $xEvent.Event.System.TimeCreated.SystemTime
            SubjectAccountName = $h.SubjectUserName
            NewAccountName = $h.TargetUserName

        } #end PSObject

    } #end Foreach-Object

} #end foreach $event
1 Like

Another advantage is a serious performance gain when using FilterHashTable. FilterXPath also does the same.

$XPath = “Event[System[EventID=4720]”

$events = Get-WinEvent -FilterXPath $XPath

In your $XPath, you can have conditionals and narrow down even further for even better performance gains.

Thank you for the information