简体   繁体   中英

How to get Virtual Machine name using VMWare API?

I'm using the Vestris.VMWareLib API to remotely control my VMs on an ESX 5.0 server. I use the VMWareVirtualMachine.Open method to power on my virtual images. My code is written in C#. The problem is that you need to know the path to the datastore before you can power on the image - I'd like to be able to power it on knowing the VM name only. Is there a way to do this? I've included my current code below. Thanks, John

using Vestris.VMWareLib;

//Works if VM name is in the path but what if it isn't?
List<VMWareVirtualMachine> vitualMachines = esxServer.RegisteredVirtualMachines.ToList();
VMWareVirtualMachine virtualMachine = vitualMachines.Where(vm => vm.PathName.Contains(vmName)).First();
VMWareVirtualMachine virtualMachine = esxServer.Open(vmName);

There's a method called VMWareVirtualMachine.GetProperty() which can be used to obtain the VM name but I don't know how to use it. Any suggestions or ideas how I can do this?

Thanks, John

There's been a commit to VMWareTasks that adds the property "Name" to the VMWareVirtualMachine class, it is taken from the "displayName" property in the vmx file. The property is not in VMWareTasks 1.7 so as of right now, you will need to pull the source and build it yourself.

Use it to iterate the registered guests, checking this variable and then power on the appropriate one.

using Vestris.VMWareLib;

private void powerOnVm(string vmName)
{
    using (VMWareVirtualHost esxServer = new VMWareVirtualHost())
    {
        esxServer.ConnectToVMWareVIServer("yourHost", "yourUser", "yourPassword");
        using (VMWareVirtualMachine virtualMachine = esxServer.RegisteredVirtualMachines.FirstOrDefault(vm => vm.Name == vmName))
        {
            if (virtualMachine != null && !virtualMachine.IsRunning)
                virtualMachine.PowerOn();
        }
    }
}

I just tested the above and it worked fine.

To simplify above answer: You don't need to recompile sources against the old commit. Just use the method call below:

GetProperty<string>(Constants.VIX_PROPERTY_VM_NAME) instead of vm.Name

(I don't have enough reputation to comment the answer, so sorry for the new one).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM