I am stuck with the following problem: we have an app that runs an continuous loop opening remote connection via powershell (performing some actions and then closing). This works fine in a Windows machine but not in Linux ones (tested on Ubuntu 16.0.4).

Use the the script below to reproduce the problem:

$i = 0
while ($i -le 200)
    $password = "myPassword"
    $domain = "domain\computerName"
    $computerName = "xxx.xxx.xxx.xxx"
    $pwSession = convertto-securestring -AsPlainText -Force $password
    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $domain,$pwSession
    $session = new-pssession -computername $computerName -credential $cred -Authentication Negotiate
    Remove-PSSession -Session $session

    sleep 3
  1. enter a powershell context by running pwsh
  2. run the script above (copy + paste)
  3. run top -p {process id} on the pwsh process id (you can run it in a single step with top -p $(ps -aux | grep pwsh | head -n 1 | cut -d' ' -f5)

You will see a window like

enter image description here

You will notice the memory consumption will keep growing (by 0.1 percent at each iteration), indefinitely.

Google does return a couple of posts mentioning memory leaks in opening new sessions with powershell, but I could not find in any of them an explanation on why the simple script above would create such an issue - again, in linux, only.

Any ideas in how tackle this issue ?

  • This does confirm memory leaks in powershell, have been trying identify which cache should I clear, if any
    – Veverke
    Apr 12, 2021 at 7:19
  • in the bug report I can see talks about doing a loop >= 1024 rather than 201 as you do. github.com/PowerShell/PowerShell/issues/…
    – A.B
    Apr 12, 2021 at 9:21
  • @A.B: have just started another session to test a 1030 iterations loop, will update. Thanks. Although... this will not be of any help... I will not wait that much iterations for the memory to start being freed...
    – Veverke
    Apr 12, 2021 at 9:31
  • @A.B: A 1030 iterations loop did not reach a point where memory starts being freed.
    – Veverke
    Apr 12, 2021 at 10:07
  • By the way, you can use pgrep instead of trying to parse ps: top -p $(pgrep -f pwsh) .
    – terdon
    Apr 12, 2021 at 10:59


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.