crysti
March 20, 2021, 3:24pm
1
Hello,
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!
Olaf
March 21, 2021, 12:59am
2
crysti,
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.
Discourse uses Markdown for text formatting. There is a reference sheet and quick tutorial here: Markdown Reference
You can produce in-line code formatting by wrapping your code in backticks (`). For example, `Get-ChildItem` produces Get-ChildItem.
For larger code blocks, place a line containing three backticks above and below your code. For example
```
# 256-Color Foreground & Background Charts
echo “`n$esc[1;4m256-Color Foreground & Background Charts$esc[0m”
foreach ($fgbg in 38,48) { #…
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*'
[PSCustomObject]@{
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.
1 Like
crysti
March 21, 2021, 10:46am
3
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 {
$h.add($_.Name,$_.'#text')
[PSCustomObject] @{
TimeCreated = $xEvent.Event.System.TimeCreated.SystemTime
SubjectAccountName = $h.SubjectUserName
NewAccountName = $h.TargetUserName
} #end PSObject
} #end Foreach-Object
} #end foreach $event
1 Like
tonyd
March 24, 2021, 4:29pm
5
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.
crysti
March 27, 2021, 5:47pm
6
Thank you for the information