Search code examples
windowsvbscriptautomationevent-logwindows-server

script to backup, compress and clear eventlogs returns negative filesize value


Here at work we have an increasing number of alerts regarding event log high usage (mostly on the security log). To solve that we've written a script that automatically copies, compresses and clears the eventlog, and added it as a scheduled task.

So far so good and its been working great on many servers.

However, when the log maximum filesize is set to 2097152 kB or above the function returns a negative value (most likely because it goes offrange since it returns it as bytes).

The extraction of the code that is failing is as follows:

Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate, (Backup, Security)}!\\" & strServer & "\root\cimv2")
For Each Item in oWMI.ExecQuery("SELECT * FROM Win32_NTEventLogFile WHERE LogFileName='Security'")
    Report = Report & vbNewLine & " " & Item.LogFileName & " log" & vbNewLine & _
             "  Maximum size: " & (Item.MaxFileSize/1024) & " KB" & vbNewLine & _
             "  Current size: " & (Item.FileSize/1024) & " KB" & vbNewLine & _
             "  Usage percentage: " & _
             Round(((Item.FileSize * 100) / Item.MaxFileSize),2) & vbewLine

Is there any workaround or any way to edit the code so that it supports log max file sizes of 2097152 kB and above, or is it a limitation of the GetObject() function?


Solution

  • As documented the MaxFileSize property is an unsigned 32-bit integer value:

    MaxFileSize

    Data type: uint32
    Access type: Read/write

    However, VBScript doesn't recognize unsigned data types, so the value gets misinterpreted. You need to correct it yourself, e.g. like this:

    Function FixUInt32(val)
      If val >= 0 Then
        FixUInt32 = val
      Else
        FixUInt32 = 4294967296 + val
      End If
    End Function
    

    Beware that, again as documented, having logs this large is possible, but not recommended:

    Although event logs can be sized as large as 4 gigabytes, in practice they should be limited to no more than 300 megabytes. Event logs larger than that can be difficult to analyze because of the number of events contained within the log and because event logs are not optimized for data retrieval.