vRO get all VM’s

I have been spending less time than I would like in vRO but I wanted to share some of my findings in a brief format.  Here is the code in a scriptable task that can get all virtual machines across all vCenters connected to your vRO instance.

var vCenters=VcPlugin.allSdkConnections;

 for each (vCenter in vCenters){
     System.log(vCenter.name);
     var clusters = vCenter.getAllClusterComputeResources();
     for each (cluster in clusters) {
        System.log(cluster.name);
        var vms = vCenter.allVirtualMachines
         for each (vm in vms)
           System.log(vm.name);
           //do your per vm action here
    }
}

There are better ways to gather each virtual machine but I wanted to demonstrate how to walk down the layers.  (you can just get the vm’s without getting vCenters and getting clusters I’ll show at bottom)  This code will be very familiar to PowerCLI users who do this type of action all the time.   I have included lots of system logging to help you understand the walking feel free to remove.  Some highlights are as follows

  • create an instance of the vCenter sdk called vCenters
    • From this you can call almost any vCenter sdk exposed object
  • identify vCenters one at a time into vCenter
  • identify clusters one at a time into cluster
  • identify vm’s one at a time into vm
  • Take some action on each vm

You can of course shorten this code with:

var vCenters=VcPlugin.allSdkConnections;

for each (vCenter in vCenters){
  var vms = vCenter.allVirtualMachines
    for each (vm in vms) {
      System.log(vm.name);
      //do your per vm action here
    }
}

See how that is shorter.  It’s a pretty cool feature.  One thing to remember is the returned data into vms is a object of allVirtualMachines not a text field.  It’s a multi-dimensional array of key value pairs associated with vm.   I am referencing one element of individual elements using vm.name (or single vm entity key field of name)

Enjoy and let me know if I can help.

7 Replies to “vRO get all VM’s”

  1. These few lines of code saved me! Many thanks!

    Do you have any decent resources or documentation for the vcplugin sdk? Haven’t been having much luck finding anything to work from!

    Many thanks.

  2. Thanks Joseph. One thing : in your loop “for each (cluster in clusters)” there’s no relation between the VM names you’re logging and the cluster you’re in. So… what’s the point of nesting the loops 🙂 ? Did I miss something or…

Leave a Reply

Your email address will not be published. Required fields are marked *

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