Evacuate Datastore Script When Migrating to a New SAN

One of the coolest features of VMware’s DRS is that you can place a host in maintenance mode, and VMs will just start vMotioning over to other hosts. It makes maintenance a breeze. I assumed this same functionality would exist when you place a Datastore in maintenance mode, but nope. No dice.

Here’s a script to move virtual disks off a datastore and on to a Datastore Cluster. This is useful when you are migrating to a different SAN.

I found an error when migrating, so there is a try/catch in the script to exit on error. The script will keep Storage vMotioning on failure, so a try/catch was necessary.

# Evacuate DataStore
# By Greg Carriger
#==========
# Variables
#==========
$EvacuatingDataStore = “OldDatastore”
$DestinationDataStoreCluster = “NewDatastoreCluster”
#==========
# Script
#==========
try {
Get-Datastore $EvacuatingDataStore | get-vm | ForEach-Object {
$FreeDataStore = Get-DatastoreCluster -name $DestinationDataStoreCluster | Get-Datastore | Sort-Object -Property FreeSpaceGB -Descending | Select-Object -First 1
move-vm -vm $_.Name -Datastore $FreeDataStore
Get-DatastoreCluster -name $DestinationDataStoreCluster | Get-Datastore | sort-object FreeSpaceGB -Descending | select name,FreeSpaceGB | ft
$VMsleft = (Get-Datastore $EvacuatingDataStore | get-vm | measure-object).count
Write-Output “VMs left $VMsleft”
}
}
catch {
write-output “Encountered an error. “”To resolve Operation is not valid due to the current state of the object”” error, please restart all powershell sessions.”
exit
}

Possible enhancements:

1. logging

2. Test for enough space before migrating.

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s