Reputation: 663
I'm trying to learn how to use Where-Object correctly in the below command-lines to display all processes larger than 20 megabytes.
get-process | Select-Object Name, @{Name="Private Memory (MB)"; Expression={$_.privatememorysize / 1mb}} |
Where-Object {"Private Memory (MB)" -gt 20} |
Sort-Object "Private Memory (MB)" -Descending |
format-table -autosize
I am able to kind of do it in the below command-line. However, I don't want to specify it using 20971520 bytes. I would rather like to specify it in megabytes. If that's not possible (or the command-line would get too complex), then I'd just like the output to show all processes larger than 20 MB; even if I have to specify it using bytes:
get-process | Select-Object Name, @{Name="Private Memory (MB)"; Expression={$_.privatememorysize / 1mb}} |
where-object {$_.privatememorysize -gt 20971520} |
Sort-Object "Private Memory (MB)" -Descending |
format-table -autosize
Upvotes: 1
Views: 799
Reputation: 26023
You can specify sizes literally in PowerShell:
PS C:\> 1KB
1024
PS C:\> 1MB
1048576
PS C:\> 1GB
1073741824
So you can use those literally in your code when you want to perform a mathematical operation. So if all you wanted to do was to replace that literal, go for it:
$myProcesses = get-process |
where-object { $_.privatememorysize -gt 20MB } |
select-object name, @{ Name = "Private Memory (MB)"; Expression = {$_.privatememorysize / 1MB}} |
Sort-object "Private Memory (MB)" -Descending
A note: you'll probably only want to use format-table
on an object when it is ready to be output to be read by a user. So in this case, once you're ready to output this to the screen you could simply do $myProcesses | format-table -autosize
. If you're doing this from the command line and simply want to see the results ASAP, then don't even bother with the variable and format it like you described.
Upvotes: 1
Reputation: 2917
Change
where-object {"Private Memory (MB)" -gt 20}
to
where-object {$_."Private Memory (MB)" -gt 20}
As in
get-process |
Select-Object Name, @{Name="Private Memory (MB)"; Expression={$_.privatememorysize / 1mb}} |
Where-Object {$_."Private Memory (MB)" -gt 20} |
Sort-Object "Private Memory (MB)" -Descending |
format-table -autosize
The reason you can just use 20 (vs 20mb) in your Where-Object expression is because you already specified the unit of measure in your select statement. In fact, if you use 20971520, it will think you mean 20971520 MB.
Upvotes: 1