Delete VM-Host Affinity Rules via CLI

This code will aid in the automation of deleting Host Affinity rules via PowerCLI.

Currently the Get-DRSRule and Remove-DRSRule command does not allow the removal of VM-Host Affinity rules.
This code block will get a “VMHost Affinity” rule based on a string filter then delete it along with the VM group + Host group attached to it.
If you don’t want to delete the VM and host group, just remove the sub group specs below.

Add-PSSnapin VMware.VimAutomation.Core
Connect-VIServer “” -User “XX” -password “XX”

$Mycluster = get-cluster “MyCluster”
$therules = get-drsrule -cluster $mycluster -type vmhostaffinity | where {$ -match “RuleNameHere”}

foreach($rule in $therules){
$spec = New-Object VMware.Vim.ClusterConfigSpecEx
$spec.rulesSpec = New-Object VMware.Vim.ClusterRuleSpec[](1)
$spec.rulesSpec[0] = New-Object VMware.Vim.ClusterRuleSpec
$spec.rulesSpec[0].operation = “remove”
$spec.rulesSpec[0].removeKey = $rule.key
$spec.rulesSpec[0].info = New-Object VMware.Vim.ClusterVmHostRuleInfo
$spec.rulesSpec[0] = $
$spec.rulesSpec[0].info.vmGroupName = $rule.extensiondata.vmgroupname
$spec.rulesSpec[0].info.affineHostGroupName = $rule.extensiondata.AffineHostgroupname
$spec.groupSpec = New-Object VMware.Vim.ClusterGroupSpec[](2)
$spec.groupSpec[0] = New-Object VMware.Vim.ClusterGroupSpec
$spec.groupSpec[0].operation = “remove”
$spec.groupSpec[0].removeKey = $rule.extensiondata.vmgroupname
$spec.groupSpec[0].info = New-Object VMware.Vim.ClusterVmGroup
$spec.groupSpec[0] = $rule.extensiondata.vmgroupname
$spec.groupSpec[1] = New-Object VMware.Vim.ClusterGroupSpec
$spec.groupSpec[1].operation = “remove”
$spec.groupSpec[1].removeKey = $rule.extensiondata.AffineHostgroupname
$spec.groupSpec[1].info = New-Object VMware.Vim.ClusterHostGroup
$spec.groupSpec[1] = $rule.extensiondata.AffineHostgroupname
$_this = Get-View (get-cluster $Mycluster)
$_this.ReconfigureComputeResource_Task($spec, $true)

Here are some extra vars if you want to make a report from each rule”
#The name of the Rule

#name of the VM group and host group assigned to the Rule
$vmgroupname = $rule.extensiondata.vmgroupname
$hostgroupname = $rule.extensiondata.AffineHostgroupname

#list of VMs by name in the VM Group
$vmlist = get-vm -id $rule.vmids | %{$}

#list of hosts by name in the Host group
$hostlist = get-vmhost -id $rule.AffineHostIds | %{$}

VMware Links: