Move your templates to a new cluster – The PowerCLI Way

powerclilogoAlright, here's a script I quickly pieced together to accomplish the task of moving some of our templates over to a new cluster.  At the time I was currently in the process of deploying a new cluster on a new distributed virtual switch, thus this script only tackles your templates on a single host basis.  Meaning I was walking each host over to the new switch one by one and then migrating virtual machine networking and all vmkernel interfaces on the host, then performing a vmotion on the VMs and templates and finally destroying the original host…

Oh well, enough history (blabbing).  The script is very simple as you can see below.  Aside from your vCenter information it takes a couple of variables; source and destination host (Lines 7/8).  The only quirkiness I found was with the Set-Template cmdlet – I could not find a way to specify the location of the VM when converting it, thus you can see on line 18 I have to move it back to my source host after the conversion to ensure i will have the connectivity on my migrated vMotion network.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$vcenter ='IP of vCenter'
$vcuser = 'vCenter User'
$vcpass = 'vCenter Pass'
 
Connect-VIServer $vcenter -user $vcuser -pass $vcpass
 
$sourcehost = get-vmhost 'Source Hostname/IP'
$destinationhost = get-vmhost 'Target Hostname/IP'
 
#get all templates on source host
$templates = get-template -Location $sourcehost
 
foreach ($template in $templates)
{
    # convert template to VM
    Set-Template $template -ToVM -confirm:$False
    # ensure it is running on my source host
    Get-VM -Name $template | Move-VM -Destination $sourcehost
    # migrate vm to new cluster
    Get-VM -Name $template | Move-VM -Destination $destinationhost
    # convert back to a template
    Get-VM -Name $template | Set-VM -ToTemplate -Confirm:$false
}

So that's it!  I told you it was a quickie!  Again, I don't have a secret alias of PowerCLI Man so if you have any suggestions on how to improve up on any of this let me know…

  • ramesh

    I need the script which we can deploy the template with additional configuration.Let’s assume , i have 1 template with name “template” with configuration 2 GB RAM and 2 CPU VLAN ID 50 on 192.168.1.1 host , need to create one new vm on different host 192.168.1.2 with name of “windows2k8” and need to assign the resources 4GB RAM , 5 CPU’s and VLAN ID 60 and datastore “datastore1” , if possible there is any possibilities need to assign the Ip address on deployed OS .