The PowerShell script below queries the Security event log on one or more servers for events with id 4663. When trying to retrieve all audit events for event id 4663 with the following code the computer throws the following exception: how can we to optimize this PowerShell? So I just want to fetch security event log based on specific AD Users instead of all of users. Otherwise I want to retrieve what I need.
$server = "HOSTNAME"
$out = New-Object System.Text.StringBuilder
$out.AppendLine("ServerName,EventID,TimeCreated,UserName,File_or_Folder,AccessMask")
$ns = @{e = "http://schemas.microsoft.com/win/2004/08/events/event"}
foreach ($svr in $server)
{ $evts = Get-WinEvent -computer $svr -FilterHashtable @{logname="security";id="4663"} -oldest
foreach($evt in $evts)
{
$xml = [xml]$evt.ToXml()
$SubjectUserName = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='SubjectUserName']/text()" | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty Value
$ObjectName = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='ObjectName']/text()" | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty Value
$AccessMask = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='AccessMask']/text()" | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty Value
$out.AppendLine("$($svr),$($evt.id),$($evt.TimeCreated),$SubjectUserName,$ObjectName,$AccessMask")
Write-Host $svr
Write-Host $evt.id,$evt.TimeCreated,$SubjectUserName,$ObjectName,$AccessMask
}
}
$out.ToString() | out-file -filepath C:\TEMP\4663Events.csv


Get-WinEvent. Now you can start looking for answers how to speed it up. What I know is that on a local computerGet-EventLog Security -InstanceId 4663is 100 or 1000 times faster. Try testing it in your environment. If it's also slow, consider remote PS job execution so thatGet-EventLogis executed locally on remote computers and results are sent back to yours.