如何在现有虚拟机中查询vSphere?

时间:2015-04-17 16:51:08

标签: c# vmware vsphere powercli

使用VMware.Vim库(我相信PowerCLI的一部分)我正在尝试查找vSphere中存在的特定计算机。我的代码如下所示:

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!

基本上,如果我按照SDK文档中列出的方法,我找不到该机器。如果我盲目地查询所有机器并浏览集合,我就能找到它。

我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:0)

我想通了......我在看的SDK文档中没有提到,但是添加到过滤器的字符串值不是原始字符串;它们是正则表达式。

在我的情况下,机器的名称是"Machine (Other Info)"形式。如果该字符串“按原样”传递到过滤器,它将失败。如果括号被转义,例如"Machine \\(Other Info\\)",则搜索将成功。

答案 1 :(得分:0)

您可以将Regex.Escape用于用户的输入:

var filter = new NameValueCollection { { "name", $"^{Regex.Escape(name)}$" } };