Race condition when you run Remove-VMHardDiskDrive and Add-VMHardDiskDrive commands on a virtual machine

Applies to: Hyper-V Server 2012Hyper-V Server 2012 R2Windows Server 2012 Foundation More

Symptoms


 

Assume that you're running the Remove-VMHardDiskDrive Windows PowerShell command on a virtual machine. If you run an Add-VMHardDiskDrive command during a repetitive call (a consistent loop) before Remove-VMHardDiskDrive has finished removing the current disk, the two commands enter a race condition, and you receive the following error message:

 

Add-VMHardDiskDrive : 'VMName' failed to add resources. (Virtual machine ID GUID)Cannot add 'Host diskpath = Msvm_DiskDrive.CreationClassName="Msvm_DiskDrive",DeviceID="DeviceID",SystemCreationClassName="Msvm_ComputerSystem",SystemName="Host name"'. The physical disk is already connected to the virtual machine 'VMName'. (Virtual machine ID GUID) A parameter that is not valid was passed to the operation. At line:1 char:1+ Add-VMHardDiskDrive -VMName ' ' -DiskNumber X+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : InvalidArgument: (Microsoft.HyperV.PowerShell.VMTask:VMTask)     [Add-VMHardDiskDrive], VirtualizationOperationFailedException    + FullyQualifiedErrorId : InvalidParameter,Microsoft.HyperV.PowerShell.Commands.AddVMHardDiskDriveCommand

Cause


Remove-VMHardDiskDrive is a cmdlet that deletes a hard disk drive from a virtual machine. Add-VMHardDiskDrive is a cmdlet that adds a hard disk drive to a virtual machine. These cmdlets were not designed with a way to verify that their actions were completed without the caller performing additional condition checks after the command is called.

Workaround


To work around this issue, you may want to put in place a condition check that can verify that the disk in question was removed from the virtual machine before you add disks.

There are multiple ways for checking before you add the disk:

  • Check for the "The physical disk is already connected to the virtual machine" VMName before you retry adding the disk via Add-VMHardDiskDrive after the error occurs.
  • Perform a try catch after the removal of the disk when you call the add disk routine:
    try
    {
    Add-VMHardDiskDrive -VMName VMName -DiskNumber X
    }
    Catch
    {
    Remove the disk or retry the adding
    }
  • Perform a Boolean check for true or false after the disk is removed and before you add the disk:
    If(get-vmharddiskdrive -vmname $vmdisk.VMName -ControllerNumber 1)
    {
    "true"
    }
    else
    {
    "false"
    }
  • Use WMI or a driver to verify that the disk in question is still active or not on the operating system.

Status


Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the "Applies to" section.