On a recent TAM Lab session (TAM Lab 082) I covered several methods for managing vSphere templates. At the end of the presentation we had a brief bonus method that showed using PowerCLI to clone a template to a different vCenter. This could be used once you update your primary copy of a template in vCenter1 and you wanted to make that template available in a different environment. The script used in the demo is available below.
$creds = Get-Credential
$sourceVC = Connect-ViServer t036-vcsa-01.lab.enterpriseadmins.org -Credential $creds
$destVC = Connect-ViServer core-vcenter01.lab.enterpriseadmins.org -Credential $creds
$destTemplateName = 'template-tinycore11.1_tamlabtest'
$splatNewVM = @{
Name = $destTemplateName
Template = 'template-tinycore11.1'
VMHost = 't036-vesx-01.lab.enterpriseadmins.org'
}
$vm = New-VM @splatNewVM -Server $sourceVC
$splatMoveVM = @{
VM = $vm
NetworkAdapter = (Get-NetworkAdapter -VM $vm -Server $sourceVC)
PortGroup = (Get-VirtualPortGroup -Name 'VLAN10' -Server $destVC)
Destination = (Get-VMHost 'test-esx-33.lab.enterpriseadmins.org' -Server $destVC)
Datastore = (Get-Datastore 'test-esx-33_nvme' -Server $destVC)
InventoryLocation = (Get-Folder 'vc1_TAMLab082' -Server $destVC)
}
Move-VM @splatMoveVM
Get-VM $destTemplateName -Server $destVC |
Set-VM -Name 'template-tinycore11.1-bonus' -ToTemplate -Confirm:$false
This script uses splatting to improve readability. You can read more about_Splatting here. There are a couple basic components. First we connect to both vCenters, in this case using the same credentials. We then create a new VM from template on the source side, then move that VM to the destination side, and finally rename the destination VM and convert it to a template. We did this as multiple steps as Move-VM
has additional parameters to assist with changing the destination network adapter to specify the correct portgroups and such.