BCornelissen / SCOM-WinTaskSchedulerMP

SCOM Management Pack for Windows Task Scheduler
GNU Lesser General Public License v3.0
7 stars 3 forks source link

MemoryLeak in this MP #4

Closed scherndl closed 4 years ago

scherndl commented 4 years ago

There is a memory usage problem in this managemantpack.

In our enviroment, we saw that the monitoring agents memory usage is growing and growing.

I found that the problem is in this MP, exactly in the GetTaskAndJobsProperties_2.ps1 script.

The cmdlet get-winevent with the parameter MaxEvents do not give the used memory free.

get-winevent -LogName 'Microsoft-Windows-TaskScheduler/Operational' -FilterXPath $successXPath -MaxEvents 1

My first solution was to fix it with get-winevent -LogName 'Microsoft-Windows-TaskScheduler/Operational' -FilterXPath $successXPath | Select-Object -First 1

But there is the same bug...

My next try was (get-winevent -LogName 'Microsoft-Windows-TaskScheduler/Operational' -FilterXPath $successXPath)[0]

This works, as a workaround, but needs much much more time...

I am not sure if the problem exists in every OS, you can quickly check it if you try: while(1) {get-winevent -LogName 'System' -MaxEvents 1 | Out-Null} and the look at the memory usage of the PS process. I tried it on (2012R2, 2019, Win10)

@rafabu thx for sharing this great MP

michaelsadoff commented 4 years ago

The memory leak occurs because the Get-WinEvent cmdlet doesn't clean up properly. To work around the issue, replace all Get-WinEvent lines in the script with direct calls to the EventLogReader class and run the EventLogReader.Dispose method after. For example, replace the following line:

$taskIgnoredEvent = Get-WinEvent -LogName 'Microsoft-Windows-TaskScheduler/Operational' -FilterXPath $ignoredXPath -MaxEvents 1 -ErrorAction SilentlyContinue

With:

$query = New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogQuery -ArgumentList @('Microsoft-Windows-TaskScheduler/Operational', 1, $ignoredXPath) $reader = New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogReader -ArgumentList $eventquery $taskIgnoredEvent = $reader.ReadEvent() $reader.Dispose()

scherndl commented 4 years ago

@michaelsadoff thx for your input, it works. We made a new version of this mp and send a pull request to @rafabu @rafabu please seal it with your key, so others can update their MP

BCornelissen commented 4 years ago

@scherndl Can you test the preview release 1.2.1.7? https://github.com/BCornelissen/SCOM-WinTaskSchedulerMP/releases If it works correctly please let me know so I can move to a production release. Also needs a few other changes which are not code related. Thank you!

BCornelissen commented 4 years ago

Release 1.2.2.2 is now available and should fix this Issue. Thank you all for helping out