Search code examples
c++windowsevent-log

Querying for Event Log. How to query in order to get the first and last event alone?


I've been dealing with Windows Event logs for a while. I collect the logs using the EvtQuery() function.

I'm not used to the query language. I managed to collect the entire data and render it using the EvtRender() function.

I need to get to specific data. That is, I need to add a filter to the query such that I can get the first and the last data alone. Can someone please help me with this?

edit

Here's what I've tried. As I mentioned, I'm not used to the query language. I simply didn't post the program since I didn't find it relevant to the question I asked. I'm able to fetch the complete logs using the program. Simply that I don't need the entire data.

DWORD PrintResults(EVT_HANDLE hResults);
DWORD PrintEventValues(EVT_HANDLE hEvent);

void main() {

    DWORD status = ERROR_SUCCESS;
    EVT_HANDLE hResults = NULL;
    const wchar_t *channelPath = L"Security";
    const wchar_t *query = L"*";

    //Remote handle
    EVT_HANDLE hRemoteHandle;
    EVT_RPC_LOGIN Credentials;
    RtlZeroMemory(&Credentials, sizeof(EVT_RPC_LOGIN));

    wstring comp_name = L"<ip>";
    wstring user_name = L"<username>";
    wstring password = L"<password>";

    Credentials.Server = &comp_name[0];
    Credentials.Domain = NULL;
    Credentials.User = &user_name[0];
    Credentials.Password = &password[0];
    Credentials.Flags = EvtRpcLoginAuthNTLM;
    hRemoteHandle = EvtOpenSession(EvtRpcLogin, &Credentials, 0, 0);

    hResults = EvtQuery(hRemoteHandle , channelPath, query, EvtQueryChannelPath| 
    EvtQueryForwardDirection);
    if (hResults == NULL) {                             //Check for an error
        status = GetLastError();
        if (status == ERROR_EVT_CHANNEL_NOT_FOUND)  
            cout << "ERROR : Channel not found...\n";
        else if (status == ERROR_EVT_INVALID_QUERY)
            cout << "ERROR : Invalid Query...\n";
        else
            cout << "ERROR STATUS : " << status;
        goto Cleanup;
    }

    PrintResults(hResults);

    Cleanup:
    if (hResults)
        EvtClose(hResults);
    cin.get();

}

DWORD PrintResults(EVT_HANDLE hResults) {........} //Function defined

DWORD PrintEventValues(EVT_HANDLE hEvent){........} //Function defined

Solution

  • Get the last: use EvtSeek function with parameter EVT_SEEK_FLAGS Enumeration says:

    EvtSeekRelativeToLast Seek to the specified offset from the last entry in the result set. The offset must be a negative value.

    Easy to get the first.