複数のVMSの自動スナップショットを同時にPowerCliを使用して


これはPowerShell/PowerCliスクリプトで、PowerCliを使って複数のVMのスナップショットを自動化するために書きました.圧倒的なvcenterを防ぐために、制限は同時実行タスクの最大数を指定します.

コード


    $snapshot_name = "Example Snapshot Name"
$snapshot_description = "Example Snapshot Description"
$num_concurrent_jobs_limit = 8
foreach ($vm in $vms) {
    try {
        New-Snapshot -VM $vm -Name $snapshot_name -Description $snapshot_description -Memory:$false -Quiesce:$false -RunAsync:$true -Confirm:$false -Server $vcenter_server
    } catch {
        Write-Host("Error creating snapshot for $vm on $vcenter_server.")
        $ErrorMessage = $_.Exception.Message
        Write-Host($ErrorMessage)
    }
    try {
        $current_snapshot_tasks = Get-Task | where {$_.Name -eq 'CreateSnapshot_Task' -and 'Running','Queued' -contains $_.State}
        while ($current_snapshot_tasks.count -gt $num_concurrent_jobs_limit) {
            sleep 5
            $current_snapshot_tasks = Get-Task | where {$_.Name -eq 'CreateSnapshot_Task' -and 'Running','Queued' -contains $_.State}
        }
    } catch {
        Write-Host("Error getting snapshot tasks on $vcenter_server.")
        $ErrorMessage = $_.Exception.Message
        Write-Host($ErrorMessage)
        exit
    }
}

コード説明

  • ごとに$vm イン$vms , スクリプトは、タスクが完了するのを待たずにスクリプトが継続できるようにする非同期スナップショットタスクを開始します.
  • エーwhile ループは、実行中のスナップショットタスクの数を取得するチェック/スリープサイクルを実装し、タスクの数が制限より大きい場合にスリープします.
  • スナップショットタスクの数が制限より小さい場合while ループ終了foreach ループは次のVMに進みます.
  • スクリプトはVMのスナップショットを起動できない場合はエラーメッセージを出力し、現在のスナップショットタスクを取得できない場合に終了します.
  • 資源

  • https://developer.vmware.com/powercli/
  • https://developer.vmware.com/docs/powercli/latest/products/