Tuesday, July 31, 2012

Scripting VM creation from a template with PowerCLI

This is a quick and ugly to get some VMs built in VMware.
It only does the clone from template, so at some point in the future I'll flesh it out a bit.

---
$vh = 'esxhostname'
$nm = 'vmname'
$rp = 'resource pool name'
$lo = 'folder name'
$loc = 'cluster name everything is in'
$tm = 'name of template'
$ds = 'datastore on which to put the vms'

for ($i = 1; $i -le 9; $i++){$nm = 'THISISTHENAMEOFTHEVM-0' + $i;New-vm -vmhost $vh -Name $nm -ResourcePool (get-resourcepool $rp -location (get-cluster $loc)) -Location (get-folder $lo) -Template (get-template $tm) -Datastore (get-datastore $ds)};
for ($i = 10; $i -le 20; $i++){$nm = 'THISISTHENAMEOFTHEVM-' + $i;New-vm -vmhost $vh -Name $nm -ResourcePool (get-resourcepool $rp -location (get-cluster $loc)) -Location (get-folder $lo) -Template (get-template $tm) -Datastore (get-datastore $ds)};
---

Breaking it down:

The VMs I want to create all have the same name, with the exception of a two digit trailing number.
I was lazy and made two one-liners instead of including the zero padding.

for ($i = 1; $i -le 9; $i++){$nm = 'THISISTHENAMEOFTHEVM-0'
vs
for ($i = 10; $i -le 20; $i++){$nm = 'THISISTHENAMEOFTHEVM-'

New-vm
-vmhost $vh
-Name $nm
-ResourcePool (get-resourcepool $rp -location (get-cluster $loc))
-Location (get-folder $lo)
-Template (get-template $tm)
-Datastore (get-datastore $ds)};

I struggled with this for a while until I remembered that I needed to use objects. The next hurdle was that I had a few datacenters with resource pools of the same name, so I had to add the -location on that one.

My Turn

For many years now I have gone to the web for solutions to problems, snippets of code, etc. It's my turn to contribute.