Deploy multiple VMs from templates

In my inaugural post on this blog, I’d like to present some PowerCLI code. I frequently work with customers that are transitioning from physical to virtual environments and consequently, we deploy many VMs at a time. To make this process clean and smooth, I adapted this script from Harry John to work for my purposes.

This script requires a CSV file with the information to create the VMs. This is fairly basic, so feel free to modify it to your requirements.

Title:           Deploy multiple VM
Author:          Michael Kenning ( modified from code by Harry John (
Version:         1.01
Usage:           Use with CSV file to input variables (vcserver,vmhost,vmname,datastore,template,folder)
Date Created:    17 APR 2014
Last Update:     23 APR 2014


param (

# Import the VM list
$vm_csv = Import-CSV $path
$vcserver = $vm_csv.vcserver

# Run through the CSV file and deploy the VMs

# Check to make sure the PowerCLI snap-ins are installed and connect to the vCenter Server
if(!$global:DefaultVIServer) {
	if(!(Get-PSSnapin | Where {$ -eq "vmware.vimautomation.core"})) {
		try {
			Add-PSSnapin VMware.VimAutomation.Core -ea 0| out-null
		catch {
			throw "Could not load PowerCLI snapin"
	try {
		Connect-VIServer $vcserver
	catch {
		throw "Failed to connect to VI server $vcserver"

foreach ($vm in $vm_csv) {

	# Set variables
	$vmname = $vm.vmname
	$vmhost = $vm.vmhost
	$datastore = $vm.datastore
	$template = $vm.template
	$folderName = $vm.folderName

	# Check to make sure the datastore is accessible
	if (!$datastore) {
		Write-Host "No datastore could be found. VM cannot be deployed! Aborting."
	# Check to make sure the template is valid
	if (!$template) {
		Write-Host "Template could not be found. Aborting."

	# Begin the cloning process for each VM
	Write-Host "Cloning VM ..."
	try {
	New-VM -VMHost $vmhost `
			-Name $vmname `
			-Datastore $datastore `
			-Template $template `
			-Location $folder `
			-RunAsync `
			Write-Host "An error occurred during template clone operation:"
			# output all exception information
			$_ | fl
			Write-Host "Cleaning up ..."
			# clean up and exit
			$exists = Get-VM -Name $vmname -ErrorAction SilentlyContinue
			If ($Exists){
					Remove-VM -VM $exists -DeletePermanently
	Start-VM $vm *>$null
Tagged with: ,
Posted in PowerCLI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: