jtokach
Contributor
Contributor

vCO - How to Get a VM

Hi,

How do I get an existing VM in jscript? Something like:

var vm = getVM("MyVMName");

return vm;

Sounds easy enough right? I couldn't find a single example.

Many thanks!

Jim

0 Kudos
3 Replies
cdecanini_
VMware Employee
VMware Employee

If for vCenter try:

var Pattern = 'yourVMname';
var XPath = "xpath://name[starts-with(.,'"  + yourVMname +"')]";
var VMs  = VcPlugin.getAllVirtualMachines(null, XPath);


This is from Andreas D on another post on this forum

Christophe.

If my answer resolved or helped you, please mark it as Correct or Helpful to award points. Thank you! Visit http://www.vcoteam.info & http://blogs.vmware.com/orchestrator for vCenter Orchestrator tips and tutorials - @vCOTeam on Twitter
Burke-
VMware Employee
VMware Employee

Hello Jim,

I suppose you could try something like this:

var vms = Server.findAllForType("VC:VirtualMachine","xpath:name='"+vmName+"'");
var vCenterVM = null;
if (vms != null){
    if (vms.length == 1){
        System.log("Match found for vm named: "+vmName);
        vCenterVM = vms[0];
    }else{
        System.log("More than one VM found with that name! "+vmName);
        for each (vm in vms){
            System.log("VM ID: "+vm.id);
        }
    }
}

Where your input is "vmName" of type String

and the output is vCenterVM of type VC:VirtualMachine

If you paste the code above into a Scriptable task, set the appropriate input/output, this should work. Ideally you would want to set this up as an action where you pass in a string and either get a VC:VirtualMachine object back or null back if not found. If you choose to do it that way, change the line:

vCenterVM = vms[0];

to

return vms[0];

Additionally, my first line of code could also be written as:

var vms = VcPlugin.getAllVirtualMachines(null, "xpath:name='"+vmName+"'");

since that "VcPlugin.getAllVirtualMachines" does the same as the "Server.FindAllForType("VC:VirtualMachine" ... bit of code

If my answer resolved or helped you, please mark it as Correct or Helpful to award points. Thank you! Visit http://www.vcoteam.info & http://blogs.vmware.com/orchestrator for vRealize Orchestrator tips and tutorials - @TechnicalValues on Twitter
jtokach
Contributor
Contributor

So I ended writing a custom action like this:

input params:

strVirtualMachineName

return type:

VC:VirtualMachine

var vms = System.getModule("com.vmware.library.vc.vm").getAllVMsMatchingRegexp(strVirtualMachineName);

if (vms != null & vms.length > 0) {

     for (var j = 0; j < vms.length; j++) {

          var vm = vms[j];

          // returns the first instance

          return vm;

     }

} else {

     return null;

}

Still can't believe this isn't in the API...

Thanks for your help!

Jim

0 Kudos