是否可以使用 'Like' 为 EventLogQuery 编写查询

Is it possible write query for EventLogQuery using 'Like'

我需要过滤,例如 PackageFullName 应该以“6”开头,如何使用某种模式进行过滤?

 string query = "*[System/EventID=400 ] and *[System/Opcode=2] and *[EventData[Data[@Name='PackageFullName'] LIKE '6%']]";

如评论中所述,Windows 上的事件日志服务 支持完整的 XPath 语法 - 它当然不支持 substring-matching 功能类似于 contains()/starts-with()/ends-with().

相反,您需要获取所有事件,然后通过检查您自己的代码中的数据值来过滤它们。

要从事件数据部分提取单个 <Data /> 节点的值,请使用 GetPropertyValues() method 和适当的 EventLogPropertySelector 来获取字符串值,然后手动检查它:

string logName = "Microsoft-Windows-TerminalServices-Gateway";
string queryText = "*[System/EventID=400 ] and *[System/Opcode=2] and *[EventData[Data[@Name='PackageFullName']]]";

// This is the query definition the reader will use to pre-filter event records
var query = new EventLogQuery(logName, PathType.LogName, queryText);
// This is a property selector that we'll be using to extract the event data afterwards
var packageNameSelector = new EventLogPropertySelector(new []{ "Event/EventData/Data[@Name='PackageFullName']" });

using (var reader = new EventLogReader(query))
{
    // Keep reading...
    EventLogRecord record;
    while((record = reader.ReadEvent() as EventLogRecord) is not null)
    {
        // Fetch the package name and inspect before moving ahead
        var propertyValues = record.GetPropertyValues(packageNameSelector);
        if(propertyValues.Count > 0 && propertyValues[0] is string pkgName && pkgName.StartsWith("6"))
        {
            // matching event, do what you need here 
        }
    }
}