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 “MyVcenter.pcli.me” -User “XX” -password “XX”

$Mycluster = get-cluster “MyCluster”
$therules = get-drsrule -cluster $mycluster -type vmhostaffinity | where {$_.name -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].info.name = $rule.name
$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].info.name = $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].info.name = $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
$rule.name

#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 | %{$_.name}

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

VMware Links:
http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-DrsRule.html
http://www.vmware.com/support/developer/windowstoolkit/wintk40u1/html/Remove-DrsRule.html