繁体   English   中英

如何在c#中获取计划任务的历史记录?

[英]How to get history of scheduled task in c#?

我想使用 c# 从任务调度程序中获取特定任务的历史记录。 任何人都可以帮助我。

提前致谢。

我认为Task Scheduler API不允许访问任务历史记录的原因是它保留在事件日志中。 在“任务计划程序”中检查任务历史记录时,您可以看到它的日志名称是Microsoft-Windows-TaskScheduler / Operational。 可以在事件查看器中访问相同的日志(应用程序和服务日志-> Microsoft-> TaskScheduler->操作中)

我试图使用EventLog类获取这些条目,但是显然我们不能。 我发现这篇文章暗示了一种不同的方法: https : //social.msdn.microsoft.com/Forums/en-US/882df3d5-9a9b-437b-a6ab-e09873ce6ece/cant-access-event-log-for-tasks?forum = csharplanguage

我摆弄代码只是为了看看在这种情况下是否可以使用,看起来像这样:

EventLogReader log2 = new EventLogReader("Microsoft-Windows-TaskScheduler/Operational");

for (EventRecord eventInstance = log2.ReadEvent(); null != eventInstance; eventInstance = log2.ReadEvent())
{
    if (!eventInstance.Properties.Select(p => p.Value).Contains("\\{YOUR SCHEDULED TASK NAME}}"))
    {
        continue;
    }

    Console.WriteLine("-----------------------------------------------------");
    Console.WriteLine("Event ID: {0}", eventInstance.Id);
    Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);

    try
    {
        Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
    }
    catch (EventLogException)
    {
    }

    EventLogRecord logRecord = (EventLogRecord)eventInstance;
    Console.WriteLine("Description: {0}", logRecord.FormatDescription());
}

\\ {您的计划任务名称}}可以在EventData下的日志的详细信息部分中找到。 这样,我可以找出特定任务的历史记录。

我不认为您可以运行LINQ查询并获取日期之间的条目或仅获取失败的条目等,但这可能是一个起点。

我希望这有帮助。

从以下链接下载Microsoft.Win32.TaskScheduler.dll

http://taskscheduler.codeplex.com/releases/view/120747

并将其添加为C#程序中的参考。 下面的代码获取特定计划任务的历史记录;

    using (TaskService ts = new TaskService())
    {

        TaskEventLog log = new TaskEventLog("taskPath");
        List<ListViewItem> c = new List<ListViewItem>(100);

        foreach (TaskEvent item in log)
        {
            Console.WriteLine(item.Level);
            Console.WriteLine(item.TimeCreated);
            Console.WriteLine(item.EventId);
            Console.WriteLine(item.TaskCategory);
            Console.WriteLine(item.OpCode);
            Console.WriteLine(item.ActivityId);
        }
    }

对Volkan Paksoy的答案稍作改动,即可查询网络上的远程计算机。 我还为一次性物品添加了usings

void Main()
{
    using (var session = new EventLogSession("remote server name"))
    {
        GetCompletedScheduledTaskEventRecords(session, "Your scheduled tasks name")
            .OrderByDescending(x => x.TimeCreated)
            .Select(r => new { CompletedTime = r.TimeCreated, r.TaskDisplayName, Props = string.Join(" | ", r.Properties.Select(p => p.Value)) })
            .Dump("Said Tasks Completed"); //using linqpad's Dump method, this just outputs the results to the display
    }
}
//If you don't want completed tasks remove the second part in the where clause
private List<EventRecord> GetCompletedScheduledTaskEventRecords(EventLogSession session, string scheduledTask)
{
    const int TASK_COMPLETED_ID = 102;
    var logquery = new EventLogQuery("Microsoft-Windows-TaskScheduler/Operational", PathType.LogName, "*[System/Level=4]") { Session = session };
    return GetRecords(logquery, 
        x=> x.Properties.Select(p => p.Value).Contains($@"\{scheduledTask}") && x.Id == TASK_COMPLETED_ID).ToList();
}
private IEnumerable<EventRecord> GetRecords(EventLogQuery query, Func<EventRecord, bool> filter)
{
    using (var reader = new EventLogReader(query))
    {
        for (var record = reader.ReadEvent(); null != record; record = reader.ReadEvent())
        {
            if (!filter(record)) continue;

            yield return record;
        }
    }
}
EventLogReader log2 = new EventLogReader("Microsoft-Windows-TaskScheduler/Operational");
            for (EventRecord eventInstance = log2.ReadEvent();
                null != eventInstance; eventInstance = log2.ReadEvent())
            {
                int result = DateTime.Compare(eventInstance.TimeCreated.GetValueOrDefault(), DateTime.Today.AddDays(-2));
               // do the specific task

            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM