首页 > 解决方案 > 如何在 powershell 中编写语法以重试 Foreach 循环

问题描述

我是 VMware Powercli 的新手,但我试图将脚本编写到 vMotion 集群主机中可用资源的虚拟机。在我的情况下,我有多个集群,其中启用了 HA A 并且手动配置了 DRS,并且每个主机都需要使用较新版本的 Esxi 版本进行更新。因此,要将 Esxi 主机置于维护模式,首先需要迁移 VM,一旦完成,就可以将没有 VM 的主机置于维护模式。因此,在这种情况下,我正在尝试编写将虚拟机迁移到其他主机的脚本,但是如果出现故障,这段代码会起作用吗?

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
    }
}

标签: powershellpowercli

解决方案


推荐阅读