Wednesday, 23 July 2008

PowerShell - Create X Number of VM's per Datastore

We all love the 'shell, and the VI Toolkit for Windows even more. When i finish up with some other stuff, I'll surely be pointing my C# skills at some cmdlets for that.

Anyway, there are a load of "create VM" scripts out there, I thought I'd show you one with a useful twist - create a certain number of sequentially numbered VM's per datastore. For those new to the way of the 'Shell, # is a comment (unlike batch or vbscript)
$esx = Get-VMHost -Name esx.host.name
$template = Get-Template -name TEMPLATE-NAME
$x = 1

#loop through all datastores on host
foreach ($d in Get-Datastore -vmhost $esx)
{

#check that it's not a local datastore
if (!($d.name -match ":"))
{
#loop to create 10 VM's per datastore
for ($i=$x; $i -lt ($x + 10); $i++)
{
#append a number to VM name
$vmname = "VM" + "$i";
#create the VM from template
New-VM -Name $vmname -Template $template -Datastore $d -Host $esx
}
#set $x to the next number in sequence for the next datastore
$x = $i
}
}


There you have it. The only caveat is that the datastores don't get returned by name so if you have sequentially numbered datatstores and want the VM numbers to match (ie VM1 - VM10 on 'datastore 1', VM11 - VM20 on 'datastore 2'), you'll need to pump the datastores into an array and -sort it first or something. I'll leave the intrepid reader to handle that if required :-)