Search code examples
c#virtual-machinecluster-computingwmihyper-v

How to remove virtual machine from Hyper-V cluster?


There is a cluster node on which I create virtual machine: enter image description here

After that I use method AddVirtualMachine to add existing virtual machine to cluster.

enter image description here

But there is no corresponding method DeleteVirtualMachine.

If I simply remove virtual machine from a Node, then the following artefact is left on a cluster: enter image description here

How can I remove my virtual machine from Hyper-V cluster via WMI?


Solution

  • I have decompiled Microsoft.FailoverClusters.PowerShell.dll and found out that we need to use the WMI class MSCluster_ResourceGroup.

    This is how it can be done via powershell:

    (Get-WmiObject -namespace root\mscluster -class MsCluster_ResourceGroup -filter "name='vm-name'").DestroyGroup()
    

    Here is object model for MSCluster_ResourceGroup that I use in C# code:

    public class MsResourceGroup : ManagementObjectWrapperBase
    {
        public static MsResourceGroup Create(
            ManagementObject fromResourceGroupManagementObject)
        {
            var name = fromResourceGroupManagementObject.GetStringPropertyValue("Name");
    
            return new MsResourceGroup(
                name: name,
                resourceGroupManagementObject: fromResourceGroupManagementObject);
        }
    
        private MsResourceGroup(
            string name,
            ManagementObject resourceGroupManagementObject)
            : base(resourceGroupManagementObject)
        {
            Name = name;
        }
    
        public string Name { get; }
    
        public void DestroyGroup()
        {
            AsManagementObject.Invoke(
                methodName: "DestroyGroup",
                fillInvocationParameters: inputParameters => { });
        }
    }