
Creating ِStorage DRS VM Anti-Affinity Rules via PowerCLI
When managing a VMware environment, we often rely on standard vSphere DRS rules to keep virtual machines on separate physical hosts for high availability. But what happens when you need to keep those same VMs on separate underlying storage arrays or datastores? That is where Storage DRS (SDRS) anti-affinity rules come into play.
If you have tried automating this in PowerCLI, you might have noticed that native, high-level cmdlets like New-DrsRule only apply to compute clusters, not storage clusters. To configure a datastore cluster anti-affinity rule, we have to dig a bit deeper into the vSphere API.
The most efficient way to achieve this is by using PowerShell’s New-Object command to interact directly with the VMware Vim objects. Here is how you can do it.
The Script
powershell
# Target the specific VMs and the Datastore Cluster
$vms = Get-VM -Name "vm01", "vm02"
$dsc = Get-DatastoreCluster -Name "datastoreCluster01"
# Define the anti-affinity rule property
$ruleInfo = New-Object VMware.Vim.ClusterAntiAffinityRuleSpec -Property @{
Name = "AntiAffinity_VMs"
Enabled = $true
Vm = $vms.ExtensionData.MoRef
}
# Create the rule specification and set the operation to 'add'
$ruleSpec = New-Object VMware.Vim.ClusterRuleSpec -Property @{
Operation = "add"
Info = $ruleInfo
}
# Build the Storage DRS configuration specification
$spec = New-Object VMware.Vim.StorageDrsConfigSpec
$spec.PodConfigSpec = New-Object VMware.Vim.StorageDrsPodConfigSpec
$spec.PodConfigSpec.Rule += @($ruleSpec)
# Apply the configuration to the Datastore Cluster using the StorageResourceManager
(Get-View StorageResourceManager).ConfigureStorageDrsForPod($dsc.ExtensionData.MoRef, $spec, $true)
How It Works Under the Hood
- Targeting the Objects: We first gather our target virtual machines and the datastore cluster. Because we are interacting with the lower-level API, we rely on the Managed Object Reference (
MoRef) of these objects. - Building the Rule Specs: We instantiate
ClusterAntiAffinityRuleSpecto specify that the chosen VMs must live on different datastores within the cluster. We then wrap this inside aClusterRuleSpecobject and define the operation as"add". - Applying the Changes: Storage DRS settings are managed at the “Pod” (Datastore Cluster) level. We pass our rule specification into a
StorageDrsConfigSpecand use theStorageResourceManagerview to commit the changes directly to vCenter.
While it takes a few steps to build, this nested design is incredibly efficient. It allows the API to process multiple rule additions, deletions, or configuration changes all within a single, unified request.
Using this method opens up a lot of flexibility for automating application availability templates, ensuring that critical database nodes or web servers never share the same underlying storage risks.


