Hyper-V CPU Data Collection Script

2nd Edition of Hyper-V Insider's Guide I received an e-mail from someone looking for an electronic version of the VMCPU PowerShell reporting script I wrote for our book on Hyper-V, so I thought I would post it here (FYI the updated, 2nd edition is due out in a month or two!).

I wrote to script to address CPU performance monitoring requirements I had in citations where I didn’t have SCVMM or SCOM.  When we wrote the first edition of the book, James O’Neill’s PowerShell library for Hyper-V didn’t include any functions to check VM CPU load. 

James (a 5 star rated PowerShell expert, as far as I’m concerned) has since added Get-VMProcessor to the library, but I like my little function, because the output is more colorful (yes, the code is uglier than James’, but it’s my ugly baby!).

Output from VMCPU Function

Let me know if you have any questions (or just check out the end of Chapter 10 in either edition of the book!).

-John

function Report-VMCPU {Param ($server=".")
$LoadSum = 0
$PCores = 0
$VProcs= GWMI -computerName $server –Namespace root\virtualization -Class MSVM_Processor

write-host " "
write-host " CPU Load"
write-host "VM Name # %"
write-host "-------------------------------------- ---- -----"
foreach ($VProc in $VProcs) {
$VM = GWMI -computerName $server -Namespace root\virtualization -Query "Select * From MSVM_ComputerSystem Where Name = '$($VProc.SystemName)'"

$VMname = $VM.Elementname.PadRight(39," ")
$VMCPU = $VProc.deviceid.split("\")[-1]
$VMCPULOAD = $VProc.LoadPercentage
Write-Host "$VMname $VMCPU " -nonewline
if ($VMCPULOAD -lt 30) {write-host $VMCPULOAD -backgroundcolor green}
elseif ($VMCPULOAD -gt 80) {write-host $VMCPULOAD -backgroundcolor red}
else {write-host $VMCPULOAD}
$LoadSum = $LoadSum + $VMCPULOAD
}
$PProcs= GWMI -computerName $server –Namespace root\CIMV2 -Class Win32_Processor
foreach ($PProc in $PProcs) { $PCores = $PCores + $PProc.NumberOfCores }
$VLoad = $LoadSum / $PCores
write-host " "
write-host "-----------------------------------------------------------"
Write-Host "Physical Host Virtual CPU Performance Summary" -nonewline
if($Server -ne ".") {write-host " for $Server"} else {write-host " "}
write-host " "
Write-Host " Total Physical Cores: " $PCores
Write-Host "Approx. Virt. CPU Utilization: " -nonewline
if ($VLoad -lt 30) {write-host $VLoad -backgroundcolor green}
elseif ($VLoad -gt 80) {write-host $VLoad -backgroundcolor red}
else {write-host $VLoad}
write-host "-----------------------------------------------------------"
write-host " "
}