---
title: "PowerCLI script to create Metro Cluster aware DRS groups"
date: "2018-03-26T20:53:00Z"
tags: ["DRS", "Metro Cluster", "Nutanix", "PowerCLI", "PowerShell"]
categories: ["Storage & Backup", "VMware"]
---

![PowerCli][1]

In my last project, I was working with Nutanix metro cluster running on VMware ESXi. Unfortunately, Nutanix and VMware vSphere don't provide any way to automatically distribute virtual machines based on datastore to site location.<!--more-->
<!--adsense-->
One could ask why do you need to distribute or pin virtual machines to the specific datastore? The answer is quite straightforward. Let's take under the consideration following scenario.

# Suboptimal placement

Virtual machine components (CPU, RAM) are located on site B where reads/writes are on site A (traversing via network). In this situation virtual machine performance is suboptimal.
![Suboptimal Placement][2]

# Optimal placement

Virtual machine components (CPU, RAM, disk) are located on site A where reads/writes are local (not traversing via network). In this situation virtual machine performance is optimal.

![Optimal Placement][3]

## PowerCLI script to create Metro Cluster aware DRS groups

For the project needs, I created an extremely simple PowerCLI script(it is not even script, possibly some PowerCLI gurus would create a one-liner from it 😉 ). Anyway, it did work for me. As a final solution script was executed twice a day to balance the virtual machines across two sites.


```Powershell
Import-Module VMware.PowerCLI
#Importing VMware PowerCLI module

#vCenter Server connectivity details
$vcenter = IP/FQDN
$username = username
$password = password

Connect-VIServer -Server $vcenter -User $username -Password $password 
#Connecting to vCenter Server

$datastoresiteA = metroa 
#Site A datastore name

$datastoresiteB = metrob 
#Site B datastore name

$cluster = VDI
#Cluster name where we will create the DRS rules

$vmsa = Get-Datastore -name $datastoresiteA | get-vm 
#We are collecting virtual machines located on site A datastore

$vmsb = Get-Datastore -name $datastoresiteB | get-vm 
#We are collecting virtual machines located on site B datastore

Remove-DrsClusterGroup -DrsClusterGroup "DRS Group Site A" -confirm:$false
Remove-DrsClusterGroup -DrsClusterGroup "DRS Group Site B" -confirm:$false
#We are removing old DRS Rules

New-DrsClusterGroup -Name "DRS Group Site A" -VM $vmsa -Cluster $cluster
New-DrsClusterGroup -Name "DRS Group Site B" -VM $vmsb -Cluster $cluster
#We are creating new DRS Rules with new virtual machines

Disconnect-viserver * -confirm:$false
```

The script is pretty much straightforward. Simply at the beginning provide the values to connect to vCenter Server and others to make the script work.

 [1]: /images/uploads/2015/06/powercli.webp
 [2]: /images/uploads/2018/03/powercli-script-drs-suboptimal-vm-placement.webp
 [3]: /images/uploads/2018/03/powercli-script-drs-optimal-vm-placement.webp
