More DRS group automation

Following up on my last post on Automating DRS Groups with PowerCLI I found that we also need to automatically remove VMs and Hosts from a given DRS Group.

Although I could have included this in the previous script which creates the groups and adds members I wanted to separate them. There could for instance be times when you would like to run such a script on a different interval than the one that adds members as well as other scenarios. I believe it's also a good practice to build smaller scripts and functions that have more specific tasks. You could argue that the creation script also could be split up into a part that creates groups and a part that adds the members, and even maybe further splitting Hosts from VMs but that would be a future task.

Anyways, the removal of entities like Hosts and VMs from a DRS group is as easy as putting them in.

The Set-DRSClusterGroup is the cmdlet we want, now with the -Remove switch.

The following would remove the host Host-to-remove from the DRS Group Group001

Set-DrsClusterGroup -DrsClusterGroup "Group001" -VMHost "Host-to-remove" -Remove

To do the same on a VM group you just replace -VMHost with -VM and give the name of the VM

So, following the script that adds members the flow would be nearly identical.

We start by connecting to a vCenter and retrieve the clusters. Then we iterate through the clusters.

For each cluster we check for the existence of the specified DRS Cluster groups.

#Retrieve DRS group and traverse all members
$drsGroup = Get-DrsClusterGroup -Cluster $cluster -Type VMHostGroup -Name $hosttag -ErrorAction SilentlyContinue

Then, if the specified group is found we iterate through all members of the group and check the tag associations. If the specified tag is NOT found the entity is removed from the group.

foreach($member in $drsgroup.Member){
    #Initiate tag existence variable
    $hostTagExists = $false
    $hostTagAssigned = $member | Get-TagAssignment -Category "Host Attributes" #| Where-Object {$_.Tag -eq $hosttag}

    if($hostTagAssigned){
        foreach($hosttagA in $hostTagAssigned){
            if($hosttaga.Tag.Name -eq $hosttag){
                #Tag found, the host should remain a memeber of the group
                $hostTagExists = $true
            }
        }
    }
    if(!$hostTagExists){
        #Tag NOT found, the host should be removed the group
        $drsGroup | Set-DrsClusterGroup -VMHost $member -Remove #-WhatIf
        $remHosts += $member
    }
}

I add the removed hosts to an array which can be used for logging purposes.

The procedure is the same for VMs.

The full script is found on Github

This page was modified on April 1, 2019: Fixed categories and tags