I really push the limits of my Hyper-V setup. I know I am constrained by memory and am hoping to expand my network before the end of the year. But in the meantime I have to keep close tabs on memory. I thought I'd share a few commands with you. I am assuming you have the Hyper-V module installed locally. You don't have to be running a hypervisor in order to use the PowerShell commands to manage a remote server. Or you can take my commands and run them remotely via a PSSession or Invoke-Command.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
First off, I only need to get virtual machines that are currently running.
Get-VM -ComputerName chi-hvr2 | where state -eq 'running' | select Computername,VMName,MemoryAssigned,MemoryDemand,MemoryStatus
This command is using the newer Where-Object syntax. Here's a sample result.
Memory usage for running VMs
Or I can use the newer Where() method in v4 which performs better. I'll get the same result.
(Get-VM -ComputerName chi-hvr2).where({$_.state -eq 'running'}) | select Computername,VMName,MemoryAssigned,MemoryDemand,MemoryStatus
The memory values are in bytes which I'm never good at reformatting in my head, so I'll PowerShell do the work.
(Get-VM -ComputerName chi-hvr2).where({$_.state -eq 'running'}) | select Computername,VMName, @{Name="MemAssignedMB";Expression={$_.MemoryAssigned/1mb}}, @{Name="MemDemandMB";Expression = {$_.MemoryDemand/1mb}}, MemoryStatus
Formatted values
You know what? I want to take this a step further, which is usually my inclination. I think it would be useful to also see what percentage of assigned memory is being demanded. I can calculate this percentage and round to 2 decimal places.
(Get-VM -ComputerName chi-hvr2).where({$_.state -eq 'running'}) | select Computername,VMName, @{Name="MemAssignedMB";Expression={$_.MemoryAssigned/1mb}}, @{Name="MemDemandMB";Expression={$_.MemoryDemand/1mb}}, @{Name="PctMemUsed";Expression={ [math]::Round(($_.MemoryDemand/$_.memoryAssigned)*100,2)}}, MemoryStatus
Memory utilization with percentage
That should give me all of the data I need. The last step is to format the results into an easy to read report.
(Get-VM -ComputerName chi-hvr2).where({$_.state -eq 'running'}) | select Computername,VMName, @{Name="MemAssignedMB";Expression={$_.MemoryAssigned/1mb}}, @{Name="MemDemandMB";Expression={$_.MemoryDemand/1mb}}, @{Name="PctMemUsed";Expression={[math]::Round(($_.MemoryDemand/$_.memoryAssigned)*100,2)}}, MemoryStatus | Sort MemoryStatus,PctMemUsed | Format-Table -GroupBy MemoryStatus -Property Computername,VMName,Mem*MB,Pct*
Formatted VM memory report
I can take this code and turn it into a script or function to save some typing. Perhaps even parameterize for the computername. I have some other thoughts as well which I hope I can get to at some point. But for now clearly I have some issues on my Hyper-V server, CHI-HVR2, to attend to.
Enjoy!