如何使用EventLogQuery查询Eventdata?

时间:2015-07-20 01:45:44

标签: c# readeventlog

我试图通过查看安全事件日志来确定最常用户的机器。我正在使用4624事件ID,但似乎无法解决如何在查询中添加EventData的任何内容。我可以从4624事件中获取标准数据,但是我尝试查询的事件是logontype为7的事件,然后能够读取targetusername详细信息。

谢谢!

            string query = @"*[System/EventID=4624]";

            EventLogQuery eventsQuery = new EventLogQuery("Security", PathType.LogName, query);

            try
            {
                EventLogReader logReader = new EventLogReader(eventsQuery);

                for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent())
                {
                    Console.WriteLine(eventdetail.ProcessId);
                }
            }
            catch (EventLogNotFoundException)
            {
                Console.WriteLine("Error while reading the event logs");
                return;
            }

1 个答案:

答案 0 :(得分:1)

试试这个:

string query = @
"*[EventData[Data[@Name='LogonType']='7'] and System[(EventID='4624')]]";

EventLogQuery eventsQuery = new EventLogQuery("Security", PathType.LogName, query);

try {
    EventLogReader logReader = new EventLogReader(eventsQuery);

    for (EventRecord eventdetail = logReader.ReadEvent(); eventdetail != null; eventdetail = logReader.ReadEvent()) {
        string description = eventdetail.FormatDescription();
        string usernametemp = description.Substring(description.IndexOf("Account Name:") + ("Account Name:").Length + 2);
        string username = usernametemp.Substring(0, usernametemp.IndexOf("\r"));
    }
} catch (EventLogNotFoundException) {
    Console.WriteLine("Error while reading the event logs");
    return;
}

对您的查询进行排序,并使用说明查找"帐户名称"领域。希望这能回答你的问题。您可以应用该split / substring方法来真正查找该描述变量中的任何内容。它只是一个巨大的字符串 - 您在选择日志时在事件日志窗口中看到的文本。