最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to setup a Query Builder to create an Event Viewer Query based on specific Filter? - Stack Overflow

programmeradmin1浏览0评论

I wanted to create a class which has a function that will present the event viewer information. So I amu using the class EventLogQuery where my code is using the following section of the code:

eventsQuery = new EventLogQuery(logName, PathType.LogName, eventquery);

I was using before the * in the query eventquery which didn't have any issues with it. However, when the user adds some of filter settings, it always throws an error saying

"The specified query is invalid."

I created a function that will generate the query part eventquery for the EventLogQuery class and the outut was the following:

*[System[Provider[@Name='xxxxxxx' or @Name='xxxxxx'] and (Level=0 or Level=1 or Level=2 or Level=3 or Level=4) and TimeCreated[@SystemTime>='2025-03-14T09:48:11.173Z' and @SystemTime<='2025-03-28T09:48:11.173Z']]]

and as mentioned before I get the error "The specified query is invalid.". So, what is the correct syntax for the query section to be used in EventLogQuery?

Here is my querybuilder function:

private string? QueryBuilder(object? parameters)
{
    try
    {
        StringBuilder sb = new StringBuilder();
        StringBuilder eventlevels = new StringBuilder();
        StringBuilder providers = new StringBuilder();
        sb.Append("*");
        
        if (parameters != null)
        {
            var arr = (parameters as IEnumerable)?.Cast<object?>().ToList();
            string? LogName = arr[0].ToString();
            int? EventlogDateInterval = int.Parse((string)(arr[1]));
            int? eventloglevel = int.Parse((string)(arr[2]));
            string[]? EventSources = arr[3]?.ToString().Split(";");
            string? eventErrorOnly = arr[4]?.ToString();

            sb.Append("[System[");


                if (EventSources != null)
                {
                    string sourceQuery = "";

                    string[] eventSources = EventViewerSourceModel.EventSources[LogName].Split(";");

                    providers.Append("Provider[");

                    for (int i = 0; i < eventSources.Length; i++)
                    {
                        if (i == 0)
                        {
                            providers.Append($"@Name='{eventSources[i]}'");
                        }
                        else if (i == eventSources.Length - 1)
                        {
                            providers.Append($" or @Name='{eventSources[i]}']");
                        }
                        else
                        {
                            providers.Append($" or @Name='{eventSources[i]}'");
                        }
                    }

                    sourceQuery = providers.ToString();
                    sb.Append(sourceQuery);
                }
                if (eventloglevel != null)
                {
                    sb.Append(" and ");
                    string levelquery = "";
                    //[(Level = 1  or Level = 2 or Level = 3 or Level = 4 or Level = 0 or Level = 5)]]
                    if (eventErrorOnly == "Y")
                    {
                        levelquery = "(Level=2)";
                        sb.Append(levelquery);
                    }
                    else if (eventloglevel > 1)
                    {
                        int loopcnt = 0;
                        var loglevels = Enum.GetValues(typeof(EventViewerLogLevel)).Cast<EventViewerLogLevel>().Where(e => (int)e <= eventloglevel).Select(e => new { Name = e, Value = (int)e }).ToList();

                        foreach (var loglevel in loglevels)
                        {
                            if (loopcnt < 1)
                            {
                                eventlevels.Append($"(Level={loglevel.Value} ");
                            }
                            else if (loopcnt == loglevels.Count - 1)
                            {
                                eventlevels.Append($" or Level={loglevel.Value})");
                            }
                            else
                            {
                                eventlevels.Append($" or Level={loglevel.Value}");
                            }

                            loopcnt++;
                        }

                        levelquery = eventlevels.ToString();
                        sb.Append(levelquery);
                    }
                    else if (eventloglevel == 1)
                    {
                        levelquery = "(Level = 1)";
                        sb.Append(levelquery);
                    }
                    else if (eventloglevel > 5)
                    {
                        return null;
                    }
                }
                if (EventlogDateInterval != null)
                {
                    sb.Append(" and ");
                    DateTime DateNow = DateTime.Now;
                    TimeSpan datetimeInterval = TimeSpan.FromDays(Convert.ToDouble(EventlogDateInterval));
                    DateTime StartTimeGenerated = DateNow.Subtract(datetimeInterval);

                    string isoDateNow = DateNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                    string isoStartTimeGenerated = StartTimeGenerated.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

                    string timeQuery = $"TimeCreated[@SystemTime&gt;='{isoStartTimeGenerated}' and @SystemTime&lt;='{isoDateNow}']";
                    sb.Append(timeQuery);
                }
            }

            sb.Append("]]");

            return sb.ToString();
        }
        else
        {
            return sb.ToString();
        }
    }
    catch (Exception ex)
    {
        return null;
    }
}

for the eventLogSources, I am using a static class (EventViewerSourceModel.EventSources) which holds the source and is in dictionary where the key is the logname. So to grab the sources,it can be done in powershell using following scripts and each source has ; to split them from each other:

$logs = "Application", "System", "Security", "Setup"

foreach ($log in $logs) {
>>     Write-Output "Log: $log"
>>     Get-WinEvent -ListLog $log | Select-Object -ExpandProperty ProviderNames
>>     Write-Output "---------------------------------"
>> }

For the log event levels, here is the enum

    public enum EventViewerLogLevel
    {
        Info,
        Critical,
        Error,
        Warning,
        Information,
        Verbose,
        None
    }

Would it be best to do filtering after getting the results from *?

Update

I manage to narrow down issue to the provider names, I already tested the Event Level and Date and they worked fine. The cause of the error is due to the provider names. Can the Query handle multiple provider names? or does it need to be only one provider?

发布评论

评论列表(0)

  1. 暂无评论