title: How to Write syntax in powershell for retry the Foreach loop
body: <p>I am new to VMware Powercli but i was trying to write the script to vMotion the Virtual machine within in cluster host where resources are available. In my case I have multiple cluster where HA A is enabled and DRS is configured Manual and each host need to be updated with newer version of Esxi version. Hence to put the Esxi host in maintenance mode VMs need to be migrated first and once that is done then Host without VM can be placed in Maintenance Mode. So in this context I am trying to write the Script which will migrate the VMs to other host but incase of failure will this code work?</p>
  <pre><code>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 &gt;$null
      $clusterhosts = Get-Cluster $cluster_name | Get-VMHost | Where-Object { $_.name -notlike &quot;$source_host&quot; }
      $vms = Get-VMHost $source_host | Get-VM
      $vmcount = $vms.count
      if ($vmcount -eq 0) {
          Write-Host &quot;Host Does Not found any VM&quot;
          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 &gt;$null #-ErrorAction stop
          }
          
          break
      }
  }
  </code></pre>