Search code examples
c#vmwarevspherepowercli

How do I query vSphere for an existing virtual machine?


Using the VMware.Vim library (part of PowerCLI I believe) I'm trying to find a specific machine that exists in vSphere. My code looks like this:

using VMware.Vim;
var client = new VimClient();
client.Connect("http://my-vsphere/sdk");
client.Login("username", "password");

var filter = new NameValueCollection();
filter.Add("name", "my-vm-name");
var vms1 = client.FindEntityViews(typeof(VirtualMachine), null, filter, null);
// vms1 is null here. WTF?

var vms2 = client.FindEntityViews(typeof(VirtualMachine), null, null, null);
foreach (VirtualMachine vm in vms)
{
    if(vm.Name = "my-vm-name")
    {
        Console.WriteLine("Found it!");
    }
}
// This works!

Basically if I follow the method outlined in the SDK documentation, I can't find the machine. If I blindly query for all of the machines and walk through the collection, I can find it.

Am I missing something here?


Solution

  • I figured it out... This isn't mentioned in the SDK documentation that I was looking at, but the string values added to the filter are not raw strings; they are regular expressions.

    In my situation, the name of the machine was in the form, "Machine (Other Info)". If that string is passed into the filter "as-is" it will fail. If the parentheses are escaped, like "Machine \\(Other Info\\)" the search will succeed.