CSV format
| Name | Template | Cluster | Datastore | ESXi | Customization | vCpu | Memory | Location | Network | HDsize1 | HDsize2 | IP | Subnetmask | Gateway | DNS1 | DNS2 |
Script:
#PowerCLI to create multiple VMs from template
Add-PSSnapin vmWARE.VimAutomation.Core
$vc="vcname
"
connect-viserver $vc
#Import VM information
$VMs = Import-CSV "C:\NewVMs.csv
"
foreach ($vm in $vms){
#Assign Variables
$VMName = $vm.Name
$Template = $vm.Template
$Cluster = $vm.Cluster
$Datastore = $vm.Datastore
$Custom = $vm.Customization
$vCPU = $vm.vCPU
$Memory = $vm.Memory
$Location = $vm.Location
$ESXi = $vm.ESXi
$Network = $vm.Network
$HDsize1=$vm.HDsize1
$HDsize2=$vm.HDsize2
$IP=$vm.IP
$Subnetmask=$vm.subnetmask
$Gateway=$vm.Gateway
$DNS1=$vm.DNS1
$DNS2=$vm.DNS2
#Create VM from template
New-VM -Name $VMName -Template $Template -VMHost $ESXi -Datastore $Datastore -Location $Location -OSCustomizationSpec $Custom
#Change VM's vCPU, Memory, NetworkAdapter
$NewVM = Get-VM -Name $VMName
$NewVM | Set-VM -MemoryGB $Memory -NumCpu $vCPU -Confirm:$false
$NewVM | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $Network -Confirm:$false
$NewVM | New-Harddisk -CapacityGB $HDsize1 -StorageFormat EagerZeroedThick -Confirm:$false
$NewVM | New-Harddisk -CapacityGB $HDsize2 -Confirm:$false
#Set VM IP, Subnetmask, Gateway, DNS
$NewVM | Start-VM
sleep -Seconds 60
$NewVM | Restart-VM -confirm:$false
sleep -Seconds 240
Write-Host "Setting IP address for $NewVM..." -ForegroundColor Yellow
Sleep -Seconds 40
$netsh = "c:\windows\system32\netsh.exe interface ip set address ""Ethernet"" static $IP $Subnetmask $Gateway"
$netsh2 = "c:\windows\system32\netsh.exe interface ip set dnsservers ""Ethernet"" static $DNS1"
$netsh3 = "c:\windows\system32\netsh.exe interface ip add dnsservers ""Ethernet"" $DNS2"
Invoke-VMScript -VM $NewVM -GuestUser administrator -GuestPassword 1111abcd!
-ScriptType bat -ScriptText $netsh
Invoke-VMScript -VM $NewVM -GuestUser administrator -GuestPassword 1111abcd!
-ScriptType bat -ScriptText $netsh2
Invoke-VMScript -VM $NewVM -GuestUser administrator -GuestPassword 1111abcd!
-ScriptType bat -ScriptText $netsh3
Write-Host "Setting IP address completed." -ForegroundColor Green
}
Disconnect-VIServer -Confirm:$false
本文转自学海无涯博客51CTO博客,原文链接http://blog.51cto.com/549687/2048193如需转载请自行联系原作者
520feng2007