Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return only the integer sum of Measure-Object in PowerShell?

Tags:

powershell

If I run the following command in PowerShell, it will return to me an object with the sum of the WorkingSet property:

PS > get-process chrome | measure-object WorkingSet -sum

Count    : 36
Average  :
Sum      : 2377129984
Maximum  :
Minimum  :
Property : WorkingSet

If I want to return just the Sum value, the only way I've found to do it is:

PS > $a = get-process chrome | measure-object WorkingSet -sum
PS > $a.Sum
2359980032

Is there a way to pipe the original command to some other command so that I return the integer in a single step? Something like this:

PS > get-process chrome | measure-object WorkingSet -sum | {some other command}
like image 657
Ben McCormack Avatar asked Sep 13 '11 20:09

Ben McCormack


3 Answers

Yes, use Select-Object:

Get-Process chrome | Measure-Object WorkingSet -sum | Select-Object -expand Sum

Select-Object is used when one needs only some properties from the original object. It creates a new object and copies the desired properties to the new one.

Get-Process | Select-Object -property ProcessName, Handles

In case you need to extract the value (from one property), you use parameter -expandProperty instead of -property:

Get-Process | Select-Object -expand ProcessName

Note that you can compute the returned value:

get-process | Select-Object -property @{Name='descr'; Expression={"{0} - {1}" -f $_.ProcessName, $_.Handles }}
like image 124
stej Avatar answered Nov 17 '22 19:11

stej


Just use parentheses to enclose the piped command:

(get-process chrome | measure-object WorkingSet -sum).sum

As a rule, PowerShell treats anything enclosed in parentheses as an object that you can reference by properties/methods.

like image 22
JNK Avatar answered Nov 17 '22 20:11

JNK


Another way:

(get-process chrome | measure-object WorkingSet -sum).sum
like image 4
Shay Levy Avatar answered Nov 17 '22 20:11

Shay Levy