PowerCLI: Export, Import and Create DRS Rules


I was trying to create a DRS Rule creation script but after a short search on the PowerCLI communities, I found some excellent stuff from @LucD. These are two scripts for Exporting and importing DRS rules.

To export your DRS-Rules, you can run the next script. The only thing you have to change is <cluster-name> to your cluster name.

$outfile = "C:\rules.txt" Remove-Item $outfile $clusterName = <cluster-name> $rules = get-cluster -Name $clusterName | Get-DrsRule foreach($rule in $rules){ $line = (Get-View -Id $rule.ClusterId).Name $line += ("," + $rule.Name + "," + $rule.Enabled + "," + $rule.KeepTogether) foreach($vmId in $rule.VMIds){ $line += ("," + (Get-View -Id $vmId).Name) } $line | Out-File -Append $outfile }


The import script looks like this:


$file = "C:\rules.txt"
$rules = Get-Content $file

foreach($rule in $rules){
  $ruleArr = $rule.Split(",")
  if($ruleArr[2] -eq "True"){$rEnabled = $true} else {$rEnabled = $false}
  if($ruleArr[3] -eq "True"){$rTogether = $true} else {$rTogether = $false}
  get-cluster $ruleArr[0] | `
    New-DrsRule -Name $ruleArr[1] -Enabled $rEnabled `
    -KeepTogether $rTogether `
    -VM (Get-VM -Name ($ruleArr[4..($ruleArr.Count - 1)])) 


If you want to create a new DRS-Rules, you only have to create your own rules.txt file like this:



Now run the Import DRS-Rules script and in a blink of an eye, the new rules are created.


Source: http://communities.vmware.com/thread/195733?start=10&tstart=0