I've been writing some white papers for Netwrix recently and thought I'd take a snippet from one of those and share with you here. It was a small part of the How to Track User Activity with AD Auditing and PowerShell white paper but I believe it showed a great way to pull data from event logs that isn't so easily gotten.

The task at hand was when a couple of audit policies were enabled and apply to a group of computers you needed a way to find when a user logged on and logged off of a computer. I needed results that showed the computer name, the event, the time it happened and what account it was.

If you've messed with AD auditing before you'd know that the data it generates is great but it's a major pain to get to any useful information. Using PowerShell, I managed to put together an ugly (yet working) solution to get the data I needed.

## Find all computers in the My Desktops OU
$Computers = (Get-ADComputer -SearchBase 'OU=My Desktops,DC=lab,DC=local' -Filter * | Select-Object Name).Name

## Build the Xpath filter to only retrieve event IDs 4647 or 4648 $EventFilterXPath = "(Event[System[EventID='4647']] or Event[System[EventID='4648']])"

## Build out all of the calculated properties ahead of time to pull the computer name, the event of "Logon" or "Logoff", the time the event was generated and the account in the message field. �If the ID is 4647, we need to find the first instance of "Account Name:" but if it's 4648 we need to find the second instance. �Regex groupings are ugly but powerful.
$SelectOuput = @(
    @{n='ComputerName';e={$_.MachineName}},
    @{n='Event';e={if ($_.Id -eq '4648') { 'Logon' } else { 'LogOff'}}},
    @{n='Time';e={$_.TimeCreated}}, @{n='Account';e={if ($_.Id -eq '4647') { $i = 1 } else { $i = 3 } [regex]::Matches($_.Message,'Account Name:\s+(.*)\n').Groups[$i].Value.Trim()}}
)

## Query all the computers and output all the information we need
foreach ($Computer in $Computers) {
    Get-WinEvent -ComputerName $Computer -LogName Security -FilterXPath $EventFilterXPath | Select-Object $SelectOuput | Format-Table -AutoSize
}

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!