通过vSphere PowerCLI脚本批量自动部署虚拟机1.下载并安装PowerCLI
2.修改PowerCLI执行脚本的策略,允许执行任意脚本;初次运行PowerCLI时提示以下报错
通过get-executionpolicy查看本地执行策略,Restricted是禁止执行任何脚本;
修改本地执行策略set-executionpolicy RemoteSigned,允许执行任意脚本;
关闭窗口,重新运行PowerCLI
3.创建脚本
$vc = '10.0.66.7' #VCenter IP
Connect-VIServer -Server $vc -username "administrator@vsphere.local" -Password "vmware"
$vmhost="192.168.1.10" #esxi host
$namestart="test" #vm名称前缀
$template="win2012_temp" #vm模板
$datastore="64.170" #存储lun
$custsysprep = Get-OSCustomizationSpec Win#自定义规范文件
$ipstart="192.168.1." #IP前缀
$endipscope=100..150#IP后缀
#循环生成50台虚拟机
foreach ($endip in $endipscope)
{
$ip=$ipstart+$endip
$name=$namestart+$endip
$custsysprep | Set-OScustomizationSpec -NamingScheme fixed -NamingPr efix $name
$custsysprep | Get-OSCustomizationNicMapping | Set-OSCustomizationNic Mapping -IpMode UseStaticIP -IpAddress $ip -SubnetMask 255.255.255.0 -Dns 19 2.168.1.1 -DefaultGateway 192.168.1.1
New-vm -vmhost $vmhost -Name $name -Template $template -Datastore $datastore -OSCustomizationspec $custsysprep }
4.执行脚本
将上面的脚本保存为“test.ps1”,然后打开VMWare vSphere PowerCLI,切换到存放脚本的目录运行".\test.ps1"回车即可运行。
在执行脚本时,请不要关闭PowerCLI窗口,脚本执行完成后再关闭。