vRO Get VM Object By Name

When working on VM’s deployed by vRA, vRO needs to operate on a VM object. This scriptable task will find a VM object by searching the vCenter inventories by the input VM name. The result will be a single VM object. The task will fail if anything other than a single powered on VM is found with the name. SRM placeholders are excluded by checking if the powerstate is not on.

// Input is vm_name (string), output is vm_object (vc:virtualmachine)
// Needs to find only 1 VM matching the name in the inventory
// This version skips powered off VM’s (SRM placeholders)

var qry = "xpath:name='" + vm_name + "'";
var vms_found = Server.findAllForType("VC:VirtualMachine", qry);
var good_vms = [];

System.log("Number of VM's found: " + vms_found.length);
for(var i = 0; i < vms_found.length; i++){
    System.log("vCenter is " + vms_found[i].parent.parent);
    if(vms_found[i].state == "poweredOn"){
        System.log("Status is " + vms_found[i].state) + " adding to good vm's array.";

if(good_vms.length == 1){
    vm_object = good_vms[0];
} else {
    throw("Number of powered on VM's found with the name " + vm_name + " is not 1. Exiting!");
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

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.