image 

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.

#DRS-export-rules.PS1
$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:

#DRS-import-rules.PS1

$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:

<cluster-name>True,True,<vmname>,<vmname2>,<vmname3>

<cluster-name>,False,True,<vmname>,<vmname2>

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

Advertisement

3 thoughts on “PowerCLI: Export, Import and Create DRS Rules

  1. OMG. You totally ignore the rich, object-oriented approach of Powershell by parsin textfiles while importing/exporting!

    Try:
    help Export-CliXml
    help Import-CliXml
    Or, if you don’t like typing a xml for creating a new DRS rule:
    help Import-Csv

    I consider the scripts in your post the “quick and dirty” way.

    Wait a second, the nice and clean way is even quicker! Let’s see:
    Export:
    Get-Cluster (Read-Host “Cluster Name”) | Get-DrsRule | Export-CliXml ‘d:\scripts\drs.xml’
    Import:
    ForEach ($rule in (Import-CliXml ‘d:\scripts\drs.xml’)){New-DrsRule -Name $rule.Name -Enabled $rule.Enabled -KeepTogether $rule.KeepTogether -VM (Get-VM $rule.VmIds)}
    (off the top of my head)

    Hugo (http://www.peetersonline.nl)

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.