Thursday 11 August 2011

Checks for VMs with set memory limit

#Description: This powershell function checks for VMs with resource memory limit set
#Purpose: Memory limit can cause balooning and generally should not be set for the VM
#Designed to be added as function into $profile for quick-admin tasks, run from commandline

#Requires VCLI snapin -
function func_VMs_with_Limited_Memory()
{
$noConnection = $true
if ($defaultVIServers) {
 $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]@('Name','Description','OperatingSystem','IPAddress','DNSName','PowerState','CPUCount','Memory(MB)','HDDCount','NICCount','ParentHost'))
 $PSStandardVMMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
 foreach ($managedHost in $defaultVIServers) {
  $noConnection = $false
  Get-VM -Server $managedHost | ForEach-Object {
   $vmName = $_.Name
   trap {
    Write-Warning "VM $vmName Ecnountered and Error: $_"
    continue
   }
   Get-VMResourceConfiguration -VM $_ | where {$_.MemLimitMB -ne -1 } | ForEach-Object {
     $_.PSObject.TypeNames.Insert(0,"$($_.PSObject.TypeNames[0])#VmwarePowerPackExtension")
    $_ | Add-Member -MemberType NoteProperty -Name VMName -Value $vmName
    $_ | Add-Member -MemberType scriptProperty -Name "CPU Limit (Mhz)" -Value {if ($this.CpuLimitMhz -eq -1) {"Unlimited"} else {$this.CpuLimitMhz}}
    $_
   }
  }
 }
}
if ($noConnection) {
 Show-MessageBox -Text 'You must connect to one or more vSphere servers before you can run the VMs with Limited Memory best practice query on those servers. Please click on the ''Managed Hosts'' node, connect to one or more of the vSphere servers you have configured there, and then try again.' -Caption 'Connection not established' -Buttons 'OK' -Icon 'Information' | Out-Null
}

}

 func_VMs_with_Limited_Memory | Select-Object -property 'VMName', 'NumCpuShares', 'CpuReservationMhz', 'CpuSharesLevel', 'NumMemShares', 'MemReservationMB', 'MemLimitMB', 'MemSharesLevel', 'DiskResourceConfiguration', 'HTCoreSharing', 'CpuAffinity'
www.vmware.com/support/developer/vcli/
#Author: Kirk Munro, extracted from VMware powerpack: http://www.powergui.org/entry.jspa?externalID=1802&categoryID=290
#Tested with: ESX4.1
#Last edit by: MsMiller on 11/08/2011