Storage vMotion of a template

0 Flares Twitter 0 Facebook 0 LinkedIn 0 Email -- 0 Flares ×

If you try to run storage vmotion against a template, you will realize it’s not allowed in the GUI.

So, you end up with two solutions:

– “quick and dirty”: convert template to VM, run Storage vMotion, convert back VM to template

– “SysAdmin style”, useful if you have several templates: using PowerCLI run this script, it does the same tasks of the “quick and dirty” but without manual activity (thanks to this post for the hint!)

$vmName = $args[0]
$dsName = $args[1]

function Move-VMTemplate{
    param( [string] $template, [string] $datastore)

    if($template -eq ""){Write-Host "Enter a Template name"}
    if($datastore -ne ""){$svmotion = $true}

    Write-Host "Converting $template to VM"
    $vm = Set-Template -Template (Get-Template $template) -ToVM 

    Write-Host "Migrate $template to $datastore"
    # Move-VM -VM (Get-VM $vm) -Destination (Get-VMHost $esx) -Datastore (Get-Datastore $datastore) -Confirm:$false
    Move-VMThin (Get-VM $vm) (Get-Datastore $datastore)

    Write-Host "Converting $template to template"
    (Get-VM $vm | Get-View).MarkAsTemplate() | Out-Null

function Move-VMThin {
         [Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Virtual Machine Objects to Migrate")]
        ,[Parameter(Mandatory=$true,HelpMessage="Destination Datastore")]

 Begin {
        #Nothing Necessary to process
 } #Begin

    Process {
        #Prepare Migration info, uses .NET API to specify a transformation to thin disk
        $vmView = Get-View -ViewType VirtualMachine -Filter @{"Name" = "$VM"}
        $dsView = Get-View -ViewType Datastore -Filter @{"Name" = "$Datastore"}

        #Abort Migration if free space on destination datastore is less than 50GB
        if (($ / 1GB) -lt 50) {throw "Move-ThinVM ERROR: Destination Datastore $Datastore has less than 50GB of free space. This script requires at least 50GB of free space for safety. Please free up space or use the VMWare Client to perform this Migration"}

        #Prepare VM Relocation Specificatoin
        $spec = New-Object VMware.Vim.VirtualMachineRelocateSpec
        $spec.datastore =  $dsView.MoRef
        $spec.transform = "sparse"

        #Perform Migration
        $vmView.RelocateVM($spec, $null)
    } #Process

Move-VMTemplate $vmName $dsName

To run it, connect to vCenter and run the script, giving as parameters the template name and target datastore.

Here is the result: