Wednesday, March 20, 2013

PowerCLI - Batch move templates

While preparing for configuring DPM on one of the clusters, I noticed that templates are scattered around all the hosts. A design best practice for DPM states to put all your templates on one host and disable DPM on that host - this way you will not get the surprise of not being able to access some of your templates because the host was powered off. Remembering that I decided to bring all templates in one place. First I took a look at PowerCLI cmdlets - get-template and move-template and hoped for an easy job. However the cmdlets are a bit tricky:
  • get-template - documentation states that it takes as input for Location "vSphere container objects (such as folders, data centers, and clusters) you want to search for templates". It is partialy true, since it does not accept clusters, but it accepts hosts;
  • move-template -  Destination parameter used to "specify a container object where you want to move the templates" accepts only Datacenters and Folders.
My use case is input a cluster name and consolidate all templates on a single host. The next best thing was to use the cmdlets above and make my little script. The script takes as input 2 parameters: cluster and destination host. It gets all templates from cluster, converts them to VMs, migrates the VMs to destination host and reconverts them to template.

Function MoveTemplate()
{
Param(
[Parameter(Mandatory=$True,Position=0)][string]$cluster,
[Parameter(Mandatory=$True,Position=1)][string]$dsthost
)
get-cluster $cluster | get-vmhost | foreach {
get-template -Location $_ | foreach {
Write-Host "moving $_"
get-vm (set-template -Template $_ -ToVM).Name | move-vm -Destination $dsthost | set-vm -ToTemplate -Confirm:$false 
}
}
}

MoveTemplate

2 comments:

Anonymous said...

Nice! Been looking for this (and trying to write a script to do this) for a while now!

David Jhon said...

Great article with excellent idea!Thank you for such a valuable article. I really appreciate for this great information. login joker123