How do I get the raw number of bytes for a PID on Windows CLI?

With lots of research, I've got to this point:

tasklist /fi "pid eq 13584" /fo CSV

Output:

"Image Name","PID","Session Name","Session#","Mem Usage"
"php.exe","13584","Console","1","25 660 K"

Still an ugly mess. I'm trying to get output such as:

25660000

That is, no CSV or other "formatting"/unwanted data. No "formatted" amount of memory. Just raw bytes.

How is it done?


Solution 1:

cmd is not the greatest way to do this in a modern system. Powershell is far more versatile and, once you get used to the syntax and symantics, far more powerful.

For example, to list all the processes in a system:

PS C:\Users\user> Get-Process

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    325      20    10328      28056       0.28  17868   2 ApplicationFrameHost
    208      15     7308      12952      22.95  12092   0 audiodg
    476      33    26572      15592     106.06   8852   2 BorderlessGaming
    155      11     1792       7600              4132   0 BtwRSupportService
     53       4      672       2980              5096   0 cdarbsvc_v1.0.0_x64
    142       7     1616       9092       0.05  17728   2 CompPkgSrv
... etc

From there you can list a specific PID:

PS C:\Users\user> Get-Process -PID 12092

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    208      12     7308      12952      31.48  12092   0 audiodg

PM = Private Memory
WS = Working Set

To get only the memory:

PS C:\Users\user> (Get-Process -PID 12092).WorkingSet
13217792
PS C:\Users\user> (Get-Process -PID 12092).PrivateMemorySize
7413760

If you have powershell available on your system you can use it to run the command and return it to cmd:

cmd> powershell.exe -command "(Get-Process -PID 12092).PrivateMemorySize"
7598080

There are some suggestions that powershell may not properly output when run from certain environments and needs you to use Write-Output as well as -InputFormat none so try

powershell.exe -InputFormat none -command "Write-Output((Get-Process -PID 12092).PrivateMemorySize)"

make sure that you are properly escaping quotes and so on in your php script.