Thursday 5 August 2010

Finding 'idle' VM's in your infrastructure

Having run into a few 'high ready time' alerts recently, and suffering through a perceived lack of performance on a number of VM's, I ran through our datacentre's to see if I could find any wasteful VM's. These had been assigned 2 or 4 vCPU's and were doing nothing with them, due mostly to client requirements and/or specifications. Dropping these down to use less vCPU’s actually made some of the VM’s faster.

Result. 

Function Get-UnderUsedVM($VCServer,$FQDNCSVLocation)
#Finds all VM's with 'idle' vCPU's, that could be downgraded to less vCPU assigned
{
$VC = Connect-VIServer $VCServer
$Results = @()
$DCName = Get-Datacenter | Sort-Object
ForEach ($DC in $DCName)
{
        $ClusterName = Get-Datacenter -Name $DC.Name | get-cluster | Sort-Object
        Foreach ($ClusterEntity in $ClusterName)
        {
        $StatVM = get-cluster -Name $ClusterEntity | get-vm | Sort-Object
        ForEach ($VM in $StatVM)
            {
            $Adatarow = "" | Select Datacenter,'Cluster Name','VM Name','Assigned CPUs','CPU Used',MhzPerCPU
            $Adatarow.Datacenter = $DC.Name
            $VMView = get-vm -Name $VM | get-view
            $Adatarow.'Cluster Name' = $ClusterEntity
            $Adatarow.'VM Name' = $VMView.Name
            $Adatarow.'Assigned CPUs' = $VMView.Config.Hardware.NumCPU
            $Adatarow.'CPU Used' = $VMView.Summary.QuickStats.OverallCpuUsage
            $Adatarow.MhzPerCPU = [int]$VMView.Summary.QuickStats.OverallCpuUsage / $VMView.Config.Hardware.NumCPU
            $Results += $ADataRow
            }
        }
}
$Results | Select Datacenter,'Cluster Name','VM Name','Assigned CPUs','CPU Used',MhzPerCPU | Where { $_.'Assigned CPUs' -gt 1} | Where { $_.MhzPerCPU -lt 1000} | export-csv $FQDNCSVLocation -notype
}

If you can make it run faster, have any suggestions, or had this help you please leave a comment below.