PowerShell – Create High Volumes of VMs using Cloning

Sometimes you need to create and destroy a very high number of VMs in a short period of time (like when you’re testing out a new OS build).  I got tired of manually doing so in a vSphere environment, so I threw this little ditty together to help automate the process using PowerCLI.  The script first clones and starts an existing base build VM (with VMTools installed, which is a requirement; I tried to get away with not installing, but there was little point to this practice).  It will wait for the new VM to get an IP address (assigned via DHCP, also a requirement), connect the build media, run some scripts from the build media before disconnecting that media, and finally the VM will restart.  If the process fails at any point, it cleans up the failed VM.

Try {
  New-VM -Name Win12R2-testscan -Template Win21R2-CloneMe -VMHost VMHOST.CONTOSO.com
  Start-VM Win12R2-testscan

  while (!$ipaddress) {
    $ipaddress = (get-vm win12r2-testscan).guest.ipaddress[0]

  $cd = get-cddrive -VM win12r2-testscan
  Set-CDDrive -CD $cd -IsoPath "[ISOs] Win2012R2_Build.iso" -Connected:$true -Confirm:$False

  Invoke-VMScript -VM Win12R2-testscan -ScriptText "Copy-Item 'D:\*' 'C:\users\administrator\desktop' -Recurse ; cd C:\users\administrator\desktop ; C:\users\administrator\desktop\Start-Build.ps1" -GuestUser "administrator" -GuestPassword  "AdminPassword123"

  Set-CDDrive -CD $cd -nomedia -confirm:$False
  Restart-VMGuest -VM win12r2-testscan
Catch { Write-Warning "process failed" 
  Stop-VM -VM win12R2-testscan -Confirm:$false
  Remove-VM -VM Win12R2-testscan -DeletePermanently -Confirm:$false

Leave a Reply