Migrate VM to a new datastore

In an ESXi environment with no Storage vMotion I had the need to move a production VM from one datastore to another. As this would involve downtime, it was scheduled for an out-of-hours slot. So that I didn’t need to stay up all night and fire the process of manually, I came up with the following PowerShell/PowerCLI script. Feed it the Virtual Center host, VM Name, and Target Datastore and it will power down the VM and migrate it before powering it back on.

Here’s the script in case it’s of use to anyone…..

# Basic PowerShell/PowerCLI Script to migrate a VM from one Datastore to another when
# Storage VMotion is not available. Shuts down the VM, moves it to a new datastore
# and then returns to power state
# Original Version https://www.isjw.uk/?p=950 January 2015
# Command line arguments include the Names of the VM, the target datastore, and the VC Server

# Get Input
Param (
[Parameter(Mandatory =$True) ][string] $VIHost,
[Parameter(Mandatory =$True) ][string] $TargetDatastore,
[Parameter(Mandatory =$True) ][string] $VMName
# import vSphere PowerCLI cmdlets
# If this script is run in a PowerCLI environment, this line can be commented out
# Obviously, if PowerCLI is installed somewhere different this path should be changed.
. "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
# Connect to the Virtual Center Instance
Connect-VIServer $VIHost -WarningAction SilentlyContinue
#Find the VM
$VM=Get-VM -Name $VMName
#Shutdown the VM if it is powered on- Assuming Storage VMotion is not available
$OriginalState= $VM.PowerState
if ($OriginalState -eq "PoweredOn") {
Write-Host "Shutting Down" $VM.Name
Shutdown-VMGuest -VM $VM -Confirm:$false
#Wait for Shutdown to complete
do {
#Wait 5 seconds
Start-Sleep -s 5
#Check the power status again
$VM = Get-VM -Name $VMName
$status = $VM.PowerState
}until($status -eq "PoweredOff")
#Get the Target Datastore
$DS=Get-Datastore -Name $TargetDatastore

#Migrate the VM to the New Datastore
Move-VM -Datastore $DS -VM $VM -DiskStorageFormat Thin
#Power it on if it was on before
if ($OriginalState -eq "PoweredOn") {
Write-Host "Powering On" $VM.Name
Start-VM -VM $VM

Write-Host "Complete"


3 thoughts on “Migrate VM to a new datastore

  1. Magnus

    Know this is an old post but I’ll venture a question anyway 🙂
    I have tried using the above but get the error “The operation is not supported on the object”.
    Why? What I found is that it requires a “Storage VMotion license”. Is this so?

    1. Chris Post author

      Hi Magnus- You won’t need a Storage vMotion license to migrate a powered-off VM, but the script should be shutting down the VM before attempting the move- you’re essentially doing a cold migrate in the same way you can in the vsphere client.

      Is the VM actually powering off and staying powered off for the duration?


Leave a Reply

Your email address will not be published. Required fields are marked *