1.Windows以管理员身份打开PowerShell
2.在线安装PowerCLI
Install-Module -Name VMware.PowerCLI -Scope CurrentUser
3.忽略证书验证
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore
4.设置可执行远程脚本
Set-ExecutionPolicy RemoteSigned
5.连接至Vcenter
Connect-VIServer -Protocol https -User 'username@domain.com' -Password 'password' -Server x.x.x.x
6.准备excel变量清单,格式如下
7.在放置脚本和excel文件目录下开启PowerShell,执行如下脚本
$vms = Import-CSV .\VMlist.csv
foreach ($vm in $vms){
$Template = Get-Template $vm.template
$VMHost = Get-VMHost $vm.host
$Datastore = Get-Datastore $vm.datastore
New-VM -Name $vm.name -Template $Template -VMHost $VMHost -Datastore $Datastore -RunAsync
}
附:
① 如克隆linux模板后,有开机执行脚本进行批量修改需求,可执行类似如下脚本,excel中同样需添加新增获取的变量。在虚拟机执行脚本需要vmtools支持
$vms = Import-CSV .\VMlist.csv
foreach ($vm in $vms){
$Template = Get-Template $vm.template
$VMHost = Get-VMHost $vm.host
$Datastore = Get-Datastore $vm.datastore
New-VM -Name $vm.name -Template $Template -VMHost $VMHost -Datastore $Datastore -RunAsync
Start-Sleep -s 15
Get-VM $vm.Name | Start-VM
Start-Sleep -s 45
$cfgnet='sed -i "21s/dhcp/static/g" /etc/config/network && sed -i "21a\ \toption ipaddr '+$vm.ip+'" /etc/config/network && sed -i "23s/0.0.0.0/255.255.192.0/g" /etc/config/network && sed -i "23a\ \toption gateway '+$vm.gateway+'" /etc/config/network && /etc/init.d/network restart'
Get-VM $vm.Name | Invoke-VMScript -ScriptText $cfgnet
}
② 如需进行批量从Datastore删除,可执行类似如下脚本
$vms = Import-CSV .\VMList.csv
foreach ($vm in $vms){
Remove-VM $vm.name -DeletePermanently -RunAsync
}