Balance a Group of VMs Across Hosts

Posted: November 27, 2012 in Scripts, VMware

I had a scenario recently where a whole bunch of VDI machines were being created in the main production cluster, but there were 2 ESXi hosts outside the cluster that were going to be dedicated for VDI. I put together this little script for the VDI admins, so that they could just drop the list of all their VM names into a text file, run the script and the VMs would be be balanced across the dedicated VDI hosts.
You’ll need to replace the names of the hosts and the loation of the text file containing the VM names.

# Connect to the local vCenter Server
# Assumes that the logged in user has rights
Connect-VIServer localhost

# Set the names of the target hosts
$VDIHost1 = Get-VMHost -Name VDIESXi01.domain.local
$VDIHost2 = Get-VMHost -Name VDIESXi02.domain.local

# Get the list of VDI machine names
$AllVMs = Get-Content C:\Support\FullVDIList.txt

# Get the count for the number of VMs and then work out how many for each host
$AllVMsCount = $AllVMs.Count
[int]$NumVMsforHost1 = $AllVMsCount/2
[int]$NumVMsforHost2 = $AllVMsCount - $NumVMsforHost1

#Select the names of the VMs from the list
$VMsForHost1 = $AllVMs | Select-Object -First $NumVMsforHost1
$VMsForHost2 = $AllVMs | Select-Object -Last $NumVMsforHost2

# Move the VMs to host 1
ForEach ($VM in $VMsForHost1) {
$VMDetails = $null
$VMDetails = Get-VM -Name $VM
If ($VMDetails){
If ($VMDetails.VMHost -NotMatch $VDIHost1.Name){
$VMDetails | Move-VM -Destination $VDIHost1 -RunAsync

#Move the VMs to host 2
ForEach ($VM in $VMsForHost2) {
$VMDetails = $null
$VMDetails = Get-VM -Name $VM
If ($VMDetails){
If ($VMDetails.VMHost -NotMatch $VDIHost2.Name){
$VMDetails | Move-VM -Destination $VDIHost2 -RunAsync

# Drop the connection to vCenter
Disconnect-VIServer localhost -Force -Confirm:$false


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s