PowerCLI: Export, Import and Create DRS Rules v2


In my first post about this subject, I showed a script create by the PowerCLI Master @LucD. A couple of minutes later Hugo Peeters posted a comment why I did not used the object-oriented approach of Powershell. He also posted an example. So in this post I will show you the other way by using Export/Import-CliXml.

First we start with the export part. The following one-liner will export all the DRS Rules to a XML file:

# Export DRS
Get-Cluster -Name "Cluster_01" | Get-DrsRule | `
Export-CliXml 'C:\scripts\drs.xml'

The XML file look like this:

<?xml version="1.0" encoding="utf-16"?>
<Objs Version="" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <S N="Name">production</S>
      <B N="Enabled">true</B>
      <S N="ClusterId">ClusterComputeResource-domain-c7</S>
      <B N="KeepTogether">true</B>
      <Obj N="VMIds" RefId="1">
        <TN RefId="1">

The next one-liner will import the XML file, which we earlier created with the export one-liner. After the import, the one-liner will create a DRS rule:

# Import DRS
ForEach ($rule in (Import-CliXml 'C:\scripts\drs.xml')){
    New-DrsRule -Cluster (Get-Cluster -Name "Cluster_01") `
    -Name $rule.Name -Enabled $rule.Enabled `
    -KeepTogether $rule.KeepTogether `
    -VM (Get-VM -Id $rule.VmIds)}


If you want to see the DRS Rules for a cluster via the PowerCLI, You can run the following one-liner:

# DRS Rules One-Liner
Get-DrsRule -Cluster (Get-Cluster -Name Cluster_01) `
| Sort Name | Select Name, @{N="Enabled";E={$_.Enabled}}, `
@{N="Virtual Machines";E={$_.VMIds | % { Get-VM -Id $_ | `
% {$_.Name} }}} 

The following output will be generated:

Name Enabled KeepTogether Virtual Machines
appliances False False Nagios, vMA
production True True DC01,VC01,MC01,MAIL01

Before you can create a XML file with your new rules, you need to get the ID’s of the Cluster and the VM. You can get these ID’s via the following one-liner:

Get-VM | Sort Name | Select Name, `
@{N="VM ID";E={$_.Id}}, `
@{N="Cluster Name";E={Get-Cluster -VM $_}}, `
@{N="Cluster ID";E={Get-Cluster -VM $_ | % {$_.Id}}} | fl *

The output will look like this.


or you can export it to a CSV file:

Get-VM | Sort Name | Select Name, `
@{N="VM ID";E={$_.Id}}, `
@{N="Cluster Name";E={Get-Cluster -VM $_}}, `
@{N="Cluster ID";E={Get-Cluster -VM $_ | % {$_.Id}}} | `
Export-CSV -NoTypeInformation "D:\scripts\ps\vmids.csv"


Now you have to create a XML file. You can use a file, you created with the export DRS one-liner and change the following lines:


When you’re done with the XML file, you can run the Import DRS one-liner to import your new Rules. When you open the Cluster properties you will see that the new rule is added: