查找WMI查询的错误转义

时间:2018-06-22 09:44:27

标签: c# wmi-query

我在某处错误地逃避了wmi查询,有人可以帮助解决它吗?因为它显示无效查询

string deviceid = "Disk #0, Partition #0";
        string antecedent = @"\\" + Environment.MachineName + "\\root\\cimv2:Win32_DiskPartition.DeviceID=\"" + deviceid + "\"";
        ManagementObjectSearcher assosiaciation_query2 = new ManagementObjectSearcher("select Dependent from Win32_LogicalDiskToPartition where Antecedent = \"" + antecedent + "\"");
        foreach (ManagementObject assosiaciation_query_data2 in assosiaciation_query2.Get())
        {
            Console.WriteLine("Dependent: " + assosiaciation_query_data2["Dependent"]);
        }

谢谢。

2 个答案:

答案 0 :(得分:0)

您将2个双引号放在另外2个双引号中,这破坏了代码。您应该在先前的字符串中使用WMI转义代码:

string antecedent = @"\\" + Environment.MachineName + "\\root\\cimv2:Win32_DiskPartition.DeviceID=\\\"" + deviceid + "\\\"";

WMI收到命令后,应该是这样的:

  

\“您的设备ID \”

插入2个顶点的

可以正常工作:)示例:

Mycommand"myOtherCommand\"myvalue\""

编辑: 我完全误会了您的目标,很抱歉,您的查询中存在错误,因为“#”是使您的查询混乱的MySQL通配符(是MySql内联注释), 不,即使我使用“ aaa”之类的Ascendent,idk也不起作用,idk为什么您的where条件弄乱了代码:/。

如果使用下面的代码,它将起作用:

    string query = "select * from Win32_LogicalDiskToPartition";
    string antecedent = @"\\" + Environment.MachineName + "\\root\\cimv2:Win32_DiskPartition.DeviceID=\"" + deviceid + "\"";
        ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
        ManagementObjectCollection moCollection = moSearch.Get();

        foreach (ManagementObject mo in moCollection)
        {
            if (string.Equals(mo["Antecedent"].ToString(), antecedent))
                Console.WriteLine("Dependent: " + mo["Dependent"]);
        }

答案 1 :(得分:0)

好吧,因为在mysql中,您可以使用LIKE查找相似的表,我也读到https://msdn.microsoft.com/en-us/library/aa392263%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396可以在wmi查询中使用LIKE

string deviceid = "Disk #0, Partition #0"; ManagementObjectSearcher assosiaciation_query2 = new ManagementObjectSearcher("select Dependent from Win32_LogicalDiskToPartition where Antecedent LIKE '%" + deviceid + "%'");

所以蚂蚁仍然显示查询无效