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…..

 1# Basic PowerShell/PowerCLI Script to migrate a VM from one Datastore to another when
 2# Storage VMotion is not available. Shuts down the VM, moves it to a new datastore
 3# and then returns to power state
 4#
 5# Original Version https://www.isjw.uk/?p=950 January 2015
 6#
 7# Command line arguments include the Names of the VM, the target datastore, and the VC Server
 8
 9# Get Input
10Param (
11[Parameter(Mandatory =$True) ][string] $VIHost,
12[Parameter(Mandatory =$True) ][string] $TargetDatastore,
13[Parameter(Mandatory =$True) ][string] $VMName
14)
15# import vSphere PowerCLI cmdlets
16# If this script is run in a PowerCLI environment, this line can be commented out
17# Obviously, if PowerCLI is installed somewhere different this path should be changed.
18. "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
19# Connect to the Virtual Center Instance
20Connect-VIServer $VIHost -WarningAction SilentlyContinue
21#Find the VM
22$VM=Get-VM -Name $VMName
23#Shutdown the VM if it is powered on- Assuming Storage VMotion is not available
24$OriginalState= $VM.PowerState
25if ($OriginalState -eq "PoweredOn") {
26Write-Host "Shutting Down" $VM.Name
27Shutdown-VMGuest -VM $VM -Confirm:$false
28#Wait for Shutdown to complete
29do {
30#Wait 5 seconds
31Start-Sleep -s 5
32#Check the power status again
33$VM = Get-VM -Name $VMName
34$status = $VM.PowerState
35}until($status -eq "PoweredOff")
36}
37#Get the Target Datastore
38$DS=Get-Datastore -Name $TargetDatastore
39
40#Migrate the VM to the New Datastore
41Move-VM -Datastore $DS -VM $VM -DiskStorageFormat Thin
42#Power it on if it was on before
43if ($OriginalState -eq "PoweredOn") {
44Write-Host "Powering On" $VM.Name
45Start-VM -VM $VM
46}
47
48Write-Host "Complete"