Retrieving VM Affinity rules using PowerCLI

I was recently looking to retrieve output of various VM affinity rules for all clusters on a single vSphere server, I was able to retrieve this information using the Get-DRSRule cmdlet:

I need to invoke the cmdlet against all my clusters and to filter only to return DRS rules where the type is VM Affinity.

If (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) 
    {
    Add-PSSnapin VMware.VimAutomation.Core
    }
    
Connect-VIServer server.domain.local 
$DRSRules = Get-Cluster | Get-DrsRule | Where-Object {$_.Type -eq "VMAffinity"}

Now I have a set of DRS rules in a collection where the type is VM Affinity, I can now loop through each rule and return the information I require which in this instance is the below

  • DRS Rule Name
  • Cluster Name
  • Keep Together
  • List of VMs

We will now return this information, however in the default output the VM is referenced by the VMId and not the name, so in this isntance we will invoke the Get-View cmdlet agasint the returned VMId to retrieve the name.

ForEach ($DRSRule in $DRSRules)
    { 
    "" | Select-Object-Property @{N="Name";E={$DRSRule.Name}},
    @{N="Cluster";E={$DRSRule.Cluster.Name}},
    @{N="KeepTogether";E={$DRSRule.KeepTogether}},
    @{N="VMs";E={((Get-View-Id $DRSRule.VMIds).Name)}}
    } 

A sample of the output for a single DRS rule is as below:

Name : Keep Virtual Machines Together
Cluster : Cluster1
KeepTogether : True
VMs : vm1, vm2, vm3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s