イベントログから指定期間のイベントを取得する方法
イベントログに記録されているイベントについて、期間を指定をして取得する方法を調べました。
Const CONVERT_TO_LOCAL_TIME = True Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime") Set dtmEndDate = CreateObject("WbemScripting.SWbemDateTime") DateToCheck = CDate("2/18/2002") dtmStartDate.SetVarDate DateToCheck, CONVERT_TO_LOCAL_TIME dtmEndDate.SetVarDate DateToCheck + 1, CONVERT_TO_LOCAL_TIME strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colEvents = objWMIService.ExecQuery _ ("Select * from Win32_NTLogEvent Where TimeWritten >= '" _ & dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'") For each objEvent in colEvents Wscript.Echo "Category: " & objEvent.Category Wscript.Echo "Computer Name: " & objEvent.ComputerName Wscript.Echo "Event Code: " & objEvent.EventCode Wscript.Echo "Message: " & objEvent.Message Wscript.Echo "Record Number: " & objEvent.RecordNumber Wscript.Echo "Source Name: " & objEvent.SourceName Wscript.Echo "Time Written: " & objEvent.TimeWritten Wscript.Echo "Event Type: " & objEvent.Type Wscript.Echo "User: " & objEvent.User Wscript.Echo objEvent.LogFile Next
上記の例では、2002/2/18に発生した全てのイベントを取得することができます。
ただし、このスクリプトは、Windows XP 以上でなければ動作しません。
Windows 2000 で実行すると、下記のようなエラーが出て実行できません。
Microsoft VBScript 実行時エラー: ActiveX コンポーネントはオブジェクトを作成できません。: 'WbemScripting.SWbemDateTime'
どうやら、Windows 2000では'WbemScripting.SWbemDateTime'オブジェクトはサポートされていないようです。
調べてみると、'WbemScripting.SWbemDateTime'はローカル時刻をUTCに変換する処理を実行しているようです。
そこで、Windows 2000では下記のような関数を実装してUTC形式に変換してあげる必要があります。
Function FormatUTCDate(dDate) Dim strReturn strReturn = Year(dDate) & Right("0" & Month(dDate), 2) & Right("0" & Day(dDate), 2) strReturn = strReturn & "000000.000000+540" FormatUTCDate = strReturn End Function
最初にあげたコードをWindows 2000用に直すと
DateToCheck = CDate("2/18/2002") dtmStartDate = FormatUTCDate(DateToCheck) dtmEndDate = FormatUTCDate(DateToCheck + 1) strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colEvents = objWMIService.ExecQuery _ ("Select * from Win32_NTLogEvent Where TimeWritten >= '" _ & dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'") For each objEvent in colEvents Wscript.Echo "Category: " & objEvent.Category Wscript.Echo "Computer Name: " & objEvent.ComputerName Wscript.Echo "Event Code: " & objEvent.EventCode Wscript.Echo "Message: " & objEvent.Message Wscript.Echo "Record Number: " & objEvent.RecordNumber Wscript.Echo "Source Name: " & objEvent.SourceName Wscript.Echo "Time Written: " & objEvent.TimeWritten Wscript.Echo "Event Type: " & objEvent.Type Wscript.Echo "User: " & objEvent.User Wscript.Echo objEvent.LogFile Next Function FormatUTCDate(dDate) Dim strReturn strReturn = Year(dDate) & Right("0" & Month(dDate), 2) & Right("0" & Day(dDate), 2) strReturn = strReturn & "000000.000000+540" FormatUTCDate = strReturn End Function