用powercli练练手,需从实际案例出发,本节将使用powercli写两个demo,一个是创建模板,并根据模板创建新的虚机;另一个demo是克隆虚机。
【注意】
1、创建模板与克隆操作只能在vcenter上使用
2、powercli是 异步任务,因此需等待一个任务完成后,再去执行下一个任务。(使用 -Runasync 与 -ErrorAction stop 类似于linux中的nohup与&的使用)
一、创建模板并根据模板生成虚机
$task = Stop-VM win -Confirm:$false -ErrorAction Stop -RunAsync #停止虚机,并放后台
while( $task.state -eq "Running" ) #使用while循环时刻监控上一任务是否结束
{
$task = Get-Task -ID $task.id
} $task1 = New-Template -VM ( Get-VM win2 ) -Name "tp" -Location "nickdc" -ErrorAction Stop -RunAsync #根据虚机创建模板
while( $task1.state -eq "Running" )
{
$task1 = Get-Task -ID $task1.id
} #根据模板创建虚机
$task2 = New-VM -Name win3 -Template ( Get-Template tp) -VMHost (Get-VMHost 10.32.2.99) -Datastore (Get-Datastore datastore1) -ResourcePool testpool -ErrorAction Stop -RunAsync
while( $task2.state -eq "Running" )
{
$task2 = Get-Task -ID $task2.id
} Start-vm win3 #开启虚机
二、克隆虚机
脚本过程:确认虚机名与虚机所在的磁盘--> 连接vcenter-->关闭虚机-->克隆虚机-->开启虚机
$eap = $ErrorActionPreference
Try{
$ErrorActionPreference = 'Stop' # set vm name & clone vm name
$sourcevmname = "abcd"
$clonevmname = "123" # check vm name
$tip1 = Read-Host "make sure source vm name is $sourcevmname , if true , input 'y/Y' "
$tip2 = Read-Host "make sure clone vm name $clonevmname , if true , input 'y/Y'" if ( $tip1 -eq "y|Y" -and $tip2 -eq "y|Y" )
{
echo "please make sure vm name "
exit 1
} #connect vcentr
$vcenterip = "8.8.8.8"
$user = "[email protected]"
$passwd = "123456"
Connect-VIServer $vcenterip -User $user -Password $passwd -SaveCredentials
sleep 20 $starttime = date -Format "HH:mm:ss"
echo "start time : $starttime" #shutdown vm
echo (get-vm $sourcevmname).PowerState
if( (get-vm $sourcevmname).PowerState -eq "PoweredOn" )
{
stop-vm $sourcevmname -Confirm:$false
echo "stop vm"
sleep 30
} #clone vm
$myDatastore = Get-Datastore -Name datastore1
$vmhost = Get-VMHost -Name 10.32.2.99
$pool = Get-ResourcePool -Name testpool
echo "start clone vm..."
$task = New-VM -Name $clonevmname -VM $sourcevmname -Datastore $myDatastore -VMHost $vmhost -ResourcePool $pool -RunAsync -ErrorAction Stop
while( $task.state -eq "Running" )
{
$task = Get-Task -ID $task.id
}
echo "clone ok!" sleep 5 #start vm
echo "start vm"
start-vm $clonevmname
echo "everything ok!" $usetime = (New-TimeSpan $starttime ).TotalMinutes
$msg = "clone take {0:n0} minutes" -f $usetime
echo $msg
}
Catch{
Write-Host "error !"
Exit 1
}
Finally{
$ErrorActionPreference = $eap
}