Search code examples
python-2.7powershellwindows-10wmi

Process and subprocesses information(memory)


Get-Process -Id <pid>

returns only the information about that specific process, but what about all those which are invoked by this process.

Is there any way to know all the memory taken by a process and all processes which are created by that process?


Solution

  • In PowerShell you'd define a recursive function to enumerate the child processes of a given process:

    function Get-ChildProcesses {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
            [int[]]$ProcessId
        )
    
        Process {
            $ProcessId | ForEach-Object {
                $_
                Get-WmiObject -Class Win32_Process -Filter "ParentProcessID=$_" |
                    Select-Object -Expand ProcessId |
                    Get-ChildProcesses
            }
        }
    }
    

    then call Get-Process with those PIDs and expand the memory information:

    Get-Process -Id (Get-ChildProcesses 123) | Select-Object -Expand WorkingSet
    

    Replace WorkingSet with VirtualMemorySize if you want the total allocated virtual memory of the processes rather than the physical memory they're using at the time.


    In Python you'd use the module psutil, as Jean-François Fabre suggested in the comments.

    import psutil
    
    parent = psutil.Process(123)
    for child in parent.children(recursive=True):
        print(child.memory_info().rss)
    

    Replace rss with vms if you want the total allocated virtual memory of the processes rather than the physical memory they're using at the time.