我浏览了所有相关主题,但我没有找到答案。 我正在运行WMI查询以检索应用程序日志中最早事件的日期时间。不幸的是,下面的查询总是返回0值,但显然语法是正确的,因为没有返回错误消息。知道为什么会这样吗? 实际上c#嵌入式解决方案下载整个Eventviewer,因为我连接到远程机器,性能很糟糕。因此我选择了WMI查询
SelectQuery query = new SelectQuery("select * from Win32_NtLogEvent where Logfile ='" + logFileName + "' and RecordNumber = '1'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, opt)) {
foreach (ManagementObject mo in searcher.Get()) {
DateTime firstEventTime;
DateTime.TryParseExact(mo["TimeGenerated"].ToString().Substring(0, 12), "yyyyMMddHHmm", null, DateTimeStyles.None, out firstEventTime);
// if the time of the first entry of the application log is older that the dayback to check date
// set dayback to check to first app log entry date
logbox.writetoLogFile(this.GetType().Name, "First event time is " + firstEventTime, LogLevel.Debug);
if (firstEventTime > endDate) {
endDate = firstEventTime;
logbox.writetoLogTextbox("First eventviewer entry has date " + firstEventTime + ". Check log will stop at this date", Color.Black);
logbox.writetoLogFile(this.GetType().Name, "First eventviewer entry has date " + firstEventTime + ". Check log will stop at this date", LogLevel.Info);
}
}
}
不幸的是我现在想出来了。记录号未被重置,因此事件1自年龄以来已消失。 :(知道如何收集这些信息吗?
谢谢, 马可
答案 0 :(得分:0)
RecordNumber
是唯一标识符,并且不一定与您使用的LogFile匹配,类似于主键,并且您为每台计算机获取不同的数字msdn RecordNumber
的定义}:
所以你应该做的是获取具有特定LogFile的所有事件,按TimeGenerated排序并获取旧事件并再次搜索旧事件的编号:即:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management;
namespace WmiEventQuery
{
class Program
{
static void Main(string[] args)
{
SelectQuery query = new SelectQuery("select * from Win32_NtLogEvent where LogFile = 'Application' ");
//execute the query using WMI
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
//loop through each log found
List<EventDateTime> datetimesEvents = new List<EventDateTime>();
foreach (ManagementObject mo in searcher.Get())
{
DateTime firstEventTime;
DateTime.TryParseExact(mo["TimeGenerated"].ToString().Substring(0, 12), "yyyyMMddHHmm", null, DateTimeStyles.None, out firstEventTime);
datetimesEvents.Add(new EventDateTime
{
RecordNumber = Convert.ToInt32(mo["RecordNumber"]),
TimeGenerated = firstEventTime
});
}
int olderRecordNumber = datetimesEvents.OrderBy(p => p.RecordNumber).FirstOrDefault().RecordNumber;
SelectQuery queryUnique = new SelectQuery(
System.String.Format("select * from Win32_NtLogEvent where RecordNumber = {0}", olderRecordNumber)
);
ManagementObjectSearcher searcherUnique = new ManagementObjectSearcher(queryUnique);
foreach (ManagementObject mo in searcherUnique.Get())
{
//get the older event
Console.WriteLine(mo["Message"]);
Console.WriteLine(mo["RecordNumber"]);
}
Console.Read();
}
}
public class EventDateTime
{
public DateTime TimeGenerated { get; set; }
public int RecordNumber { get; set; }
}
}