PowerCLI Move-VM 返回失败,但 vm 仍在移动

Tec*_*yTJ 3 powershell vmware-esx vmware-vcenter vmware-vsphere powercli

我有一个脚本将虚拟机从一个数据存储移动到另一个。我还有其他逻辑来保护存储后端和结构免于过度订阅并等待在特定时间提交新请求(业务要求)。我只移动数据存储而不是主机。我在 Move-VM 周围有一个 try catch 块,因为我想处理故障。我运行脚本的前两三次只发生了一些错误,并且按我的预期进行了处理。最近 5 次移动返回错误,但虚拟机移动请求成功,如我在 vCenter 中看到的任务所示。这项工作也顺利完成。Move-VM 没有使用 RunAsync 开关。什么会导致 Move-VM 返回错误但成功提交移动请求。

$VMs = Get-VM -Name $ComputerName
$CurrentDataStores = Get-Datastore

foreach ($VM in $VMs){
   foreach ($store in $CurrentDataStores){
      if ($store.name -eq "$Datastore"){
         $rawDatastore = $store
      }
      if ($store.id -Match $VM.DatastoreIdList){
         $VMDatastore = $store.name
      } 
   }
   if ($VMDatastore -eq "$Datastore"){
      Write-Output "$VM : is already on requested Datastore"
   }
   else{
      try {
          Move-VM -VM $VM -Datastore $rawDatastore -ErrorAction Stop
      }
      catch {
         Write-OutPut "$VM : Unable to move VM to new Datastore" 
         continue
      }
   }
}

Move-VMDatastore : <VM Name> : Unable to move VM to new Datastore
At line:1 char:1
+ Move-VMDatastore -ComputerName <VM Name> -Datastore <Move TO Datastore>
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Move-VMDatastore


Move-VMDatastore : 12/24/2014 12:50:02 AM    Move-VM        Operation is not valid due to the current state of the
object.
At line:1 char:1
+ Move-VMDatastore -ComputerName <ComputerName[]> -Datastore <Datastore>
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Move-VMDatastore
Run Code Online (Sandbox Code Playgroud)

小智 5

我对这个问题的理解是,在Move-VM的实现中,PowerCLI运行了一个异步任务,获取了任务,然后Wait-Task在上面运行。

如果操作非常快,它将因此问题而失败。这是一个有根据的猜测,因为这是您Wait-Task完成任务时遇到的确切异常。

所以基本上你的问题是你的 VMware 服务器太快了......

一种解决方法是使用 -RunAsync 开关并自己实现正确的行为。就像是:

$Task = Move-VM -VM $VM -Datastore $rawDatastore -ErrorAction Stop -RunAsync
while($true)
{
    switch ($task.State)
    {
         'Success' { $Task.Result; break }
         'Error' { throw $Task.ExtensionData.Info.Error.LocalizedMessage }
         Start-Sleep 5
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:我已经看到了与 Stop-VM 和 Remove-VM 完全相同的问题,并以同样的方式解决了它们

此问题已提交给 PowerCLI 团队以进行改进:https : //powercli.ideas.aha.io/ideas/PCLI-I-208