Home > Back-end >  Need PowerShell script to compare a data in a row and script output data if not match only export th
Need PowerShell script to compare a data in a row and script output data if not match only export th

Time:08-20

I am having a PowerShell script to export the event logs from servers. And I having the some already exported data's in csv file. While running a running a script of event log export. I need to compare the a data in a row that is already exported event logs and script output data if not match then only export the not matched data.

$csvfile = Import-Csv C:\eventlogs.csv

$filter = "*[System[EventID=4740 and Provider[@Name='Microsoft-Windows-Security-Auditing']]]"
$result = Get-WinEvent -LogName Security -FilterXPath $filter | ForEach-Object {
    # convert the event to XML and grab the Event node
    $eventXml = ([xml]$_.ToXml()).Event
    # output the properties you need
    [PSCustomObject]@{
        EventRecordID = $eventXml.System.EventRecordID
        EventID       = $eventXml.System.EventID
        TimeCreated   = $eventXml.System.TimeCreated.SystemTime -replace '\.\d .*$'
        Computer      = $eventXml.System.Computer
        TargetUserName = ($eventXml.EventData.Data | Where-Object { $_.Name -eq "TargetUserName"}).'#text'
        SubjectUserName = ($eventXml.EventData.Data | Where-Object { $_.Name -eq "SubjectUserName"}).'#text'
        HOSTName = ($eventXml.EventData.Data | Where-Object { $_.Name -eq "TargetDomainName"}).'#text'
    }
}


# save as CSV file if you like
#$result | Export-Csv -Path C:\eventlogs.csv -NoTypeInformation

if ($csvfile.EventRecordID -notmatch $result.EventRecordID)

{

   $result | where {$result.EventRecordID -notmatch $csvfile.EventRecordID} | Export-Csv c:\eventlogs.csv -NoTypeInformation -Append

}

enter image description here

CodePudding user response:

Put the record ids in an array (using member-access enumeration:

$RecordIds = $csvfile.EventRecordID

And check for each entry if that is already contained in the array:

$Result |Where-Object EventRecordID -notin $RecordIds |
    Export-Csv c:\eventlogs.csv -NoTypeInformation -Append
  • Related