I am running a powershell script to get some logs. After the script ran for 3 hours, it stopped and the call to Invoke-RestMethod
threw an System.OutOfMemoryException
. Can anyone elaborate on this problem?

- 2,959
- 1
- 20
- 34

- 125
- 1
- 2
- 6
-
2Perhaps if you show us the code, we can see what is gobbling up your memory.. – Theo May 21 '20 at 10:08
-
1I have seen a lot of PowerShell scripts that are written in a C# style with huge collections of PowerShell objects. PowerShell objects are rather big as they are meant to be streamed via the pipeline (instead of collected in memory). If you starting with initializing a .Net list for your PowerShell objects or use the [`+=` operator](https://stackoverflow.com/a/60708579/1701026), you probably not properly using the pipeline and recommend you to share your code and eventually optimize it the way PowerShell is meant. – iRon May 21 '20 at 13:35
1 Answers
System.OutOfMemoryException
occurs when the maximum value of used memory for the current shell is reached. The Memory avaible for a Shell is configured in your WinRM-Settings.
To see you current Value you can read it from WSMan:localhost\Shell\MaxMemoryPerShellMB
:
Get-Item -Path WSMan:localhost\Shell\MaxMemoryPerShellMB
To change that value use following command (with the amount of memory you want to use):
Set-Item -Path WSMan:localhost\Shell\MaxMemoryPerShellMB -Value 1337
Attention:
To see and change the Value, you have to make sure you are running an elevated Shell and that the WinRM-Service is running!
You can start the Service with:
Start-Service WinRM
For more informations take a look at Learn How to Configure PowerShell Memory and WSMan Provider.
Note:
The problem is probaly, that you let the script run indefinetly.
This will lead to an OutOfMemoryException either way, since there is no good garbage Collection.
Maybe rethink on how you solve your task and either delete unused / overfilled variables or run your script every x-Times a day instead of running one script the whole time.

- 2,959
- 1
- 20
- 34
-
That is good to know, but only applies to PowerShell _remoting_ (to a machine acting as a server). I'm not aware of memory quotas applying to _local_ invocation. Can you clarify what you mean by there being no good garbage collection (I'm asking innocently)? – mklement0 May 21 '20 at 11:00
-
Instead of increasing the memory settings I would first look at optimizing your code so it doesn't run for hours and consume so much memory. (I've been able to reduce execution times of scripts which ran for 12+ hours to 5 minutes) – bluuf May 21 '20 at 11:16