h1

Quick and Dirty PowerShell to create a large number of test VMs with sequential names

February 25, 2010

 

Be gentle, I’m new to this PowerShell stuff – I have a requirement to create a large number of VMs from a template, this is the PowerShell Code I hacked together from a VMTN communities blog post – it’s not pretty but it works for me – you can play with the variables to adjust to your own environment and desired number of VMs.

In my case my template is a Linux VM setup ready to boot from a LiveCD – just so it generates some basic load when it starts up.

There is a bit of clever number formatting which I lifted from this blog post to pad the VM numbers out to 3 digits and make it tidy looking, not entirely sure I understand what it does – but it works!

I am using PowerGUI based on the info at Al’s blog here

Connect-VIServer -Server localhost >$null

#Variables
$NameVM ="vmNested-"
$NameTemplate ="TPL – vmNested-01"
$Datacenter="v.T.A.R.D.I.S"
$Datastore="SSD-iSCSI"
$ESX="vmESXi-4.lab"
$HOW_MANY_TO_CREATE=4

$Date=get-date -uformat "%Y%m%d"

$NumArray = (1..$HOW_MANY_TO_CREATE)

foreach ($number in $numArray )
{
$seqn=$number
$name =  $seqn | % {"{0:0##}"          -f $_}
$string = $NameVM + $name
echo Creating $string
New-VM -template (Get-template $NameTemplate) -Name $string -Datastore (Get-datastore $Datastore) -VMHost $ESX
}

 

The Results (40 VM’s from template – completed in about 5mins);

image image

2 comments

  1. Nice Script.

    I have a couple of suggestions that would make the code a tad more elegant, as follows:

    #Variables
    $NameVM =”vmNested-”
    $NameTemplate =”TPL – vmNested-01″
    $Datacenter=”v.T.A.R.D.I.S”
    $Datastore=”SSD-iSCSI”
    $ESX=”vmESXi-4.lab”
    $HOW_MANY_TO_CREATE=4

    $Date=get-date -uformat “%Y%m%d”

    $NumArray = (1..$HOW_MANY_TO_CREATE)

    for ([int]$seq=1;$seq -le $HOW_MANY_TO_CREATE;$seq++)
    {
    $string = $NameVM + ($seq.tostring(“0##”))
    “Creating $string”
    # Create the VM
    New-VM -template (Get-template $NameTemplate) -Name $string -Datastore (Get-datastore $Datastore) -VMHost $ESX
    }


    • Thanks Thomas, the examples you have on your site are probably the most useful I have found… thanks!



Leave a Comment