Sohlae
Sohlae

Reputation: 776

How to Add Operations in Powershell Command

I am using the following Powershell command in order to extract the name, the assigned RAM and RAM usage of each VMs in the server.

Get-VM | ft Name, Memorydemand, Memoryassigned

However the result of the memorydemand and memoryassigned are in Bytes but I want them to be in Megabytes. Is there a way for me to divide the results of the memorydemand and memoryassigned by 1048576 so that I can get their corresponding MB?

Also, is it also possible to get the average RAM Usage of a certain VM for the last one or two months? Even though Hyper-V is assigning dynamic memory, I just want to double-check.

Upvotes: 1

Views: 136

Answers (1)

user189198
user189198

Reputation:

There's a couple different approaches that I can think of to achieve this.

Use Select-Object to create calculated properties

Use the Select-Object command to create custom, calculated properties.

Get-VM | Select-Object -Property `
  Name,
  @{ Name = 'MemoryDemandMB'; Expression = { $PSItem.MemoryDemand/1MB } }, 
  @{ Name = 'MemoryAssignedMB'; Expression = { $PSItem.MemoryAssigned/1MB } } | 
  Format-Table -Property Name, MemorydemandMB, MemoryassignedMB -AutoSize

Use Add-Member to augment the objects

You can use the Add-Member command to add two new properties to the objects. This actually augments the objects, rather than simply appending the properties for the lifetime of the pipeline.

Get-VM | 
    Add-Member -MemberType ScriptProperty -Name MemoryDemandMB -Value { $this.MemoryDemand/1MB } -PassThru |
    Add-Member -MemberType ScriptProperty -Name MemoryAssignedMB -Value { $this.MemoryAssigned/1MB } -PassThru |
    Format-Table -Property Name, MemorydemandMB, MemoryassignedMB -AutoSize

Results

Here's what the output looks like on my system.

Name          MemoryDemandMB MemoryAssignedMB
----          -------------- ----------------
agent01                    0                0
agent02                    0                0
dc01                     878             1058
denver01                   0                0
london01                 877             1070
MobyLinuxVM                0                0
munich01                1228             1638
sccm01                  2213             2604
swarm01                    0                0
UbuntuDesktop              0                0

Upvotes: 1

Related Questions