概述
有时候需要大量创建虚拟机,这时候如果手动克隆等话比较耗时耗力,如果能自动化克隆需要的虚拟机,无疑是事半功倍的操作,这里记录并分享一下使用PowerShell来自动克隆虚拟机的方式,效果如下图所示

脚本
$vc = '192.168.205.253' #VCenter IP
Connect-VIServer -Server $vc -username "administrator@vsphere.local"
$vmhost = Get-VMHost "192.168.205.1"
$ResourcePool = Get-ResourcePool -Location $vmhost -Name "Resources"
$namestart="压力测试虚拟机"
$template="2019-DC-TEMP"
$datastore="ESXi01-M2-02"
$ipstart="192.168.1."
$endipscope=100..116
#循环生成虚拟机
foreach ($endip in $endipscope)
{
$custsysprep = Get-OSCustomizationSpec myCustSpec
$ip=$ipstart+$endip
$name=$namestart+$endip
$custsysprep | Set-OScustomizationSpec -NamingScheme fixed -NamingPrefix $name -Confirm:$false
$custsysprep | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $ip -SubnetMask 255.255.255.0 -Dns 192.168.1.1 -DefaultGateway 192.168.1.1 -Confirm:$false
New-VM `
-Name $name `
-Template $template `
-VMHost $vmhost `
-ResourcePool $ResourcePool `
-Datastore $datastore `
-OSCustomizationspec $custsysprep `
-Confirm:$false
Start-Sleep -Seconds 1
}