Scripting - Creare uno script per analizzare l'event viewer con PowerShell 2.0

[fonte http://blogs.technet.com/b/heyscriptingguy/archive/2012/05/29/use-powershell-to-perform-offline-analysis-of-security-logs.aspx ]


Segnalo questo quick Reference per PowerShell che Microsoft mette a disposizione
Ecco il link al documento di due pagine:


http://www.microsoft.com/en-us/download/details.aspx?id=7097


Per fare l’analisi dei log di sistema prima di tutto fa fatto un dump ed esportarlo in un formato commestibile per powershell:


“To dump the event log, you can use the Get-EventLog and the Exportto-Clixml cmdlets if you are working with a traditional event log such as the Security, Application, or System event logs. If you need to work with one of the trace logs, use the Get-WinEvent and the ExportTo-Clixml cmdlets.”


Ecco la sintassi:


Get-EventLog -LogName application | Export-Clixml \\hyperv1\shared\Forensics\edApplog.xml

“Note The % symbol is an alias for the Foreach-Object cmdlet.”


$logs = "system","application","security"

$logs | % { get-eventlog -LogName $_ | Export-Clixml "\\hyperv1\shared\Forensics\$_.xml" }


The previous commands, which retrieve the three classic event logs and export them in XML format to a network share, and the associated output (no output) are shown in the image that follows.


Con questo comando si importa il file xml e si prendono gli ultimi 5 entries:


$seclog = Import-Clixml \\hyperv1\shared\Forensics\security.xml

$seclog | select -Last 5


To view the entire contents of a specific event log entry, choose that entry, send the results to the Format-List cmdlet, and choose all of the properties. This technique is shown here.


$seclog | select -first 1 | fl *





($seclog | select -first 1).message (cerchiamo la proprietà Messaggio)
(($seclog | select -first 1).message).gettype() (otteniamo il tipo)


Ecco l’output:




Per sapere quante volte si verifica un evento si usa il seguente comando:


$seclog | ? { $_.message -match 'SeSecurityPrivilege'} | measure


Per ottenere tutti gli eventi che hanno lo stesso EventiID si usa il comando:


$seclog | ? { $_.message -match 'SeSecurityPrivilege'} | group eventid


Per invece contarli visto che sono memorizzati in un XML:


$seclog.Count


Ecco l’immagine esemplificativa:




Si usa l’opzione NoElement per rimuovere il raggruppamento delle informazioni in uscita

$seclog | group eventid -NoElement | sort count