This post is inspired by a one-liner from Alan Renouf and question from Jason Boche on Twitter. The original one-liner can be found here: http://www.virtu-al.net
The first one-liner in this post will show the Cluster name, ESX host and the total running VM’s on the host.
Get-VMHost | Select @{N="Cluster";E={Get-Cluster -VMHost $_}},Name, `
@{N="NumVM";E={($_ |Get-VM | where {$_.PowerState -eq "PoweredOn"}).Count}}
The second one-liner will return the hostname with the least running VM’s on it:
Get-VMHost | Select @{N="Cluster";E={Get-Cluster -VMHost $_}},Name,
@{N="NumVM";E={($_ |Get-VM | where {$_.PowerState -eq "PoweredOn"}).Count}} `
| Sort-Object NumVM | Select-Object Name -first 1
The next “two-liner” will return the VMHost with the least running VM’s and set the VMHost into maintenance mode. This can become handy if you want to patch a VMHost:
$ESXHost = Get-VMHost |Select @{N="Cluster";E={Get-Cluster -VMHost $_}},Name,
@{N="NumVM";E={($_ |Get-VM |where {$_.PowerState -eq "PoweredOn"}).Count}}`
|Sort-Object NumVM |Select-Object Name -first 1
Get-VMHost $ESXHost.Name |Set-VMHost -State maintenance
The last “two-liner” will return the VMHost with the least running VM’s, Set the host into maintenance mode and shutdown the VMHost:
$ESXHost = Get-VMHost |Select @{N="Cluster";E={Get-Cluster -VMHost $_}},Name,
@{N="NumVM";E={($_ |Get-VM |where {$_.PowerState -eq "PoweredOn"}).Count}}`
|Sort-Object NumVM |Select-Object Name -first 1
Get-VMHost $ESXHost.Name |Set-VMHost -State maintenance `
|%{Get-View $_.ID} |%{$_.ShutdownHost_Task($TRUE)}