Powershell – How to collect Security Event Logs for a single category via Powershell

active-directorypowershellwindows-event-logwindows-server-2003-r2

I am trying to write a script which collects security log from all of our domain controllers hourly and stores them remotely; i can collect the security logs , but is there a way to collect the security logs by category or event number from the DC? please do let me know if any additional questions.

My Code:

$Eventlogs = Get-WmiObject -Class Win32_NTEventLogFile -ComputerName $computer
Foreach($log in $EventLogs)
 {
        if($Log.LogFileName -eq "Security")
        {
            $Now = [DateTime]::Now
            $FileName = "Security" +"_"+$Now.Month+$Now.Day+$Now.Year+"_"+$Now.Hour+$Now.Minute+$Now.Second
            $path = "\\{0}\c$\LogFolder\$folder\$FileName.evt" -f $Computer
            $ErrBackup = ($log.BackupEventLog($path)).ReturnValue
            if($clear)
            { 
                if($ErrBackup -ne 0)
                {
                    "Backup failed" 
                    "Backup Error was " + $ErrBackup
                }
            }

        }
    }
         Copy-EventLogsToArchive -path $path -Folder $Folder 
} 

Best Answer

It's not that Get-EventLog doesn't get the Task Category, it's just that it's not the default behavior of the Cmdlet to display it. But the data is still there.

Import-Module ActiveDirectory
foreach($server in Get-ADComputer -Filter *)
{
    Get-EventLog -LogName Security -ComputerName $server | ? { $_.CategoryNumber -EQ 12544 }
}

This is further complicated by the fact that the Task Categories are actually in numerical format - Event Viewer uses CategoryMessageFiles to translate the category numbers into category names.

You can find the location of the CategoryMessageFiles in the registry, at HKLM\System\CurrentControlSet\services\eventlog\Security\Security (there's a subkey for each event log.)

The reason it's done this way is to make it easy for developers to create their own event logs and their own task categories for their own applications.

Here's some developer documentation on how to get CategoryMessage strings, but I know you don't want to go through all that, so the next best thing would just be to find examples of the kind of events that you want to filter for, figure out their category numbers, and then do a Switch($_.CategoryNumber) on them to translate them into what ever strings you like.

Edit: Actually scratch all that. Ignore everything I just said. This should serve you much better:

Get-WMIObject -Query "SELECT * FROM Win32_NTLogEvent WHERE LogFile='Security'" | Select EventCode, CategoryString