Windows Event Log – Correct Way to Limit Log Size

powershellscriptingwindows-event-log

I'm looking for a the best way to limit the windows event log size using PowerShell or a command line script. I want to run this script during installation of my application to increase the limit of a log deployed by the installer.

What I've tried thus far is using the limit event log command of power shell Limit-EventLog -LogName "logName" -MaximumSize xxMB however this command does not find the log.

Next, I tried using the installer to add the "File" and "MaxSize" registry entries: I created a key matching the event log's name under SYSTEM\CurrentControlSet\Services\EventLog, a string value with the name 'File', the data, the full path the log file, a dword value with the name 'MaxSize' and the data value in bytes I want to set the max size to be. This seems to work, however this makes the log show up in a funny way in the event viewer.

enter image description here

I've also noticed that the maximum log size can be changed directly form the event viewer and this this change isn't reflected in the registry at all. For example the event log "Microsoft-Windows-TaskScheduler/Operational" has a limit of 10MB but no corresponding registry entry under 'SYSTEM\CurrentControlSet\Services\EventLog'

What I'm looking for is a script that will allow me to obtain the same effect.

Best Answer

Don't change the value in the registry, this may lead to unexpected behaviour.

You can use Powershell, but not Limit-EventLog, because the documentation says that this works only on classic event logs (before Windows Vista).

The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.

You can change the event log size by modifying the object that you get with Get-WinEvent:

$targetLog = Get-WinEvent -ListLog "Company-Product-Module/Operational"
$targetLog.MaximumSizeInBytes = 2105344
$targetLog.SaveChanges()

If you don't know the exact name of the log, you can use Get-WinEvent -ListLog * to see them all