【问题标题】:How do I query vSphere for an existing virtual machine?如何在 vSphere 中查询现有虚拟机?
【发布时间】:2015-04-17 16:51:08
【问题描述】:

使用 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文档中列出的方法,我找不到机器。如果我盲目地查询所有机器并遍历集合,我可以找到它。

我错过了什么吗?

【问题讨论】:

    标签: c# vmware vsphere powercli


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用Regex.Escape 作为用户输入:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-05-26
        • 2016-01-29
        • 2014-07-26
        相关资源
        最近更新 更多