使用powercli創建模板與克隆虛機


用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 = "administrator@vsphere.com"
    $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  
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM