VMware Cloud Community
nmbgdc
Enthusiast
Enthusiast

How to write Powercli Script to move VMs and incase if failure occurs it should retry ?

Hi Guys,

I have multiple Esxi Host cluster running with Virtual machine and need to update each host with new version.

Hence i want to write the script which will migrate the running VMs which we want to update. So once VMs are migrated Host can put in maintenance mode but if VM migrate fails it should retry atleast three times and fails.

Here is the script I have tried but not sure whether it will retry incase of VM migration failure can someone please guide incase any issue-

param(
    [String] $vcenter_fqdn,
    [String] $vcenter_username,
    [String] $vcenter_password,
    [String] $cluster_name,
    [String] $source_host
)
    
$maxTries = 3
While ($maxTries -gt 0) {
  
    Connect-VIServer $vcenter_fqdn -User $vcenter_username -Password $vcenter_password -ErrorAction stop >$null
    $clusterhosts = Get-Cluster $cluster_name | Get-VMHost | Where-Object { $_.name -notlike "$source_host" }
    $vms = Get-VMHost $source_host | Get-VM
    $vmcount = $vms.count
    if ($vmcount -eq 0) {
        Write-Host "Host Does Not found any VM"
        break
    }
    else {
        Write-Host there are $vmcount number VMs found will try to Migrate
    
        foreach ($vm in $vms) {
            $targethost = $clusterhosts | Get-Random
            Move-VM -VM $vm -Destination $targethost >$null #-ErrorAction stop
        }
        
        break
    }
}

 

Tags (2)
Reply
0 Kudos
1 Reply
LucD
Leadership
Leadership

Perhaps try something like this

param(
    [String] $vcenter_fqdn,
    [String] $vcenter_username,
    [String] $vcenter_password,
    [String] $cluster_name,
    [String] $source_host
)
    
$maxTries = 3
  
Connect-VIServer $vcenter_fqdn -User $vcenter_username -Password $vcenter_password -ErrorAction stop >$null

$clusterhosts = Get-Cluster $cluster_name | Get-VMHost | Where-Object { $_.name -notlike "$source_host" }
$vms = Get-VMHost $source_host | Get-VM
$vmcount = $vms.count
if ($vmcount -eq 0) {
    Write-Host "No VMs found on $source_host"
    break
} else {
    Write-Host "Found $vmcount VMs. Will will try to Migrate those"
    foreach ($vm in $vms) {
        $try = 0
        while($try -lt $maxTries){
            $targethost = $clusterhosts | Get-Random
            Move-VM -VM $vm -Destination $targethost >$null #-ErrorAction stop
            $newVM = Get-VM -Name $vm.Name
            if($newVM.VMHost.Name -ne $targethost.Name){
                $try++
            }
            else{
                $try = $maxTries + 1
            }
        }
        if($try -eq ($maxTries)){
            Write-Host "Could not migrate $($vm.Name) after $maxTries attempts"
        }
    }
}

Disconnect-VIServer -Server $vcenter_fqdn -Confirm:$false


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos