VM Deployment with PowerCLI and .CSV

Post date: Aug 2, 2013 1:28:00 PM

Getting hundreds of VMs to roll out and properly configure descriptions, customer, dvSwitch PortGroups, mem, CPU, disks, etc... can be a pain if you're still using the GUI. This script rolls them out one at a time and can be run on multiple PowerCLI sessions to speed up the process. If DRS is configured you could roll them all out to a single host and when powered on, DRS will make an automated decision as to what host to place the VM on in the Cluster I find that simply selecting the cluster makes for less work when creating the .CSV. Converting GB to KB and MB for Disk and vMem in the script just makes for an easier File creation for VM batches. For the Datastore you can use a cluster or a specific DS. For location this puts the VM in the Folder you designate, however, if you have multiple folders with the same name you may see an error.

#####################################################################

#Create a virtual machine for each line of a specified csv file

#

# CSV format:

# VMName Location Cluster ResourcePool Datastore MemoryGB NumCpu Disk2 Description Customer Template NetworkName

#

# parameters:

# -filename to input list of vms to create

# Example:

#.\create-vms.ps1 -filename create-vms-ClientA.csv

#

# Example:

#.\create-vms.ps1 .\create-vms-ClientA.csv

#

# Version 2.0 AUG 2013 KnightUSN

#####################################################################

param(

[parameter(Mandatory = $true)]

[string[]]$filename

)

$VMs = Import-CSV $filename -UseCulture

ForEach($VM in $VMs){

$ClusterHost = Get-Cluster $VM.Cluster | Get-VMHost | Where {$_.ConnectionState -eq "Connected"} | Get-Random

New-vm -VMhost $ClusterHost -Name $VM.VMName -ResourcePool (Get-cluster $VM.Cluster | Get-ResourcePool $VM.ResourcePool) -Location $VM.Location -Datastore $VM.Datastore -Template $VM.Template -Description $VM.Description -DiskStorageFormat "Thin"

Get-VM $VM.VMName | Set-CustomField -Name Customer -Value $VM.Customer

$vMEM = [int]$VM.MemoryGB*[math]::pow(2,10)

Set-VM -VM $VM.VMName -MemoryMB $vMEM -NumCpu $VM.NumCpu -Confirm:$false

Get-NetworkAdapter -VM $VM.VMName | Set-NetworkAdapter -NetworkName $VM.NetworkName -confirm:$false

If ([int]$VM.Disk2 -gt 1){

$Disk2 = [int]$VM.Disk2*[math]::pow(2,20)

Get-VM $VM.VMName | New-HardDisk -CapacityKB $Disk2 -Persistence persistent

}

}