3
6

More than 3 years have passed since last update.

【PowerShell】イベントログをCSVファイルとして出力する

Last updated at Posted at 2020-09-07

経緯

Windowsサーバの点検業務にイベントログの確認があり、毎回各サーバへリモデして確認するのは面倒なので
CSVへ出力するスクリプトを作成しました。
エラー以上のログでフィルタリングしています。

変数定義

デスクトップ配下のEventLogsフォルダを指定している。ない場合は作成される
今回は1日ごとにログ取得することを想定して昨日の日付を取得

#任意の出力先フォルダと-afterで指定する時間を設定
$OutPutFolder = Join-Path ([Environment]::GetFolderPath('Desktop')) "EventLogs"
if(!(Test-Path $OutPutFolder)){ mkdir $OutPutFolder }
$yesterday = (Get-Date).Date.AddDays(-1)

Get-EventLogを使用するやり方

EntryType -eq "0"とはレベルが「重大」であるログ。

#Systemログ、Applicationログを別々に$OutPutFolderへ保存する処理。
@("System", "Application") | %{
    Get-EventLog $_ -After $yesterday |
    ?{ ($_.EntryType -eq "Error") -or ($_.EntryType -eq "0") } |
    Export-Csv -Encoding Default -NoTypeInformation -Path (
        Join-Path $OutPutFolder ($_ + "Log_" + (Get-Date).Date.ToString("yyyyMMdd") + ".csv") #任意の出力ファイル名
    )
}

Get-WinEventを使用するやり方

こっちの方がいいかも
上のスクリプトではSystemとApplicationで別ファイルに分けていたがこちらは1つのファイルですむ
Level=1,2について、1「重大」2「エラー」3「警告」4「情報」が配列で指定できる

Get-WinEvent -FilterHashtable @{
    LogName='System', 'Application'
    Level=1,2
    StartTime=$yesterday
} | 
Select-Object -Property * |
Export-Csv -Encoding Default -NoTypeInformation -Path (
        Join-Path $OutPutFolder ("WinEventLog_" + (Get-Date).Date.ToString("yyyyMMdd") + ".csv") #任意の出力ファイル名
    )

-FilterHashtable @{}でいろいろフィルターできて便利。しかも早い。
フィルタリングの仕方についてこちらのページがとても参考になりました。

上記のスクリプトではすべてのプロパティをCSVへ出力しています。
Get-WinEventSelect-Objectにて選択できるプロパティは下記。

Message
Id
Version
Qualifiers
Level
Task
Opcode
Keywords
RecordId
ProviderName
ProviderId
LogName
ProcessId
ThreadId
MachineName
UserId
TimeCreated
ActivityId
RelatedActivityId
ContainerLog
MatchedQueryIds
Bookmark
LevelDisplayName
OpcodeDisplayName
TaskDisplayName
KeywordsDisplayNames
Properties

余談

Get-EventLogでは表示できないMassege内容が、Get-WinEventでは見えたりする。
(Get-WinEventからパイプでExport-Csvに渡すと改行が混じって列がずれる。それを直すスクリプトを書かなければならなくなる。)
CSVに改行コードが混じるのは確かだけれどエクセルで表示した際はきちんと列がずれなかったのでこれでよいのかな。

当初はGet-EventLogの方が簡単だと思ってたけど、やってみたらGet-EventLogの方がシンプルで早くてよかったかもしれない。

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6