如何在WMI查询中转义字符

时间:2015-08-13 08:12:17

标签: c# wmi

我尝试使用以下代码创建WMI查询:

string query = "ASSOCIATORS OF {Win32_DiskDrive.PNPDeviceID='" + device["PNPDeviceID"].ToString().Replace(@"\", @"\\")
                        + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";

但如果query变量看起来像ASSOCIATORS OF {Win32_DiskDrive.PNPDeviceID='USBSTOR\\DISK&VEN_FLASH&PROD_DRIVE_SM_USB20&REV_1100\\7214030310011150&0'} WHERE AssocClass = Win32_DiskDriveToDiskPartition,它会给我“无效的对象路径”异常。

为什么呢?我究竟做错了什么?我该如何解决?

然后在WMI查询中转义所有字符的适当方法是什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

选择错误的属性来查询ASSOCIATORS OFWin32_DiskDriveToDiskPartition类表示磁盘驱动器与其上存在的分区与下一个关系属性之间的关联:

==>wmic path Win32_DiskDriveToDiskPartition get /value

Antecedent="\\PC\root\cimv2:Win32_DiskDrive.DeviceID="\\.\PHYSICALDRIVE1""
Dependent="\\PC\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #0""

Antecedent="\\PC\root\cimv2:Win32_DiskDrive.DeviceID="\\.\PHYSICALDRIVE1""
Dependent="\\PC\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #1""

Antecedent="\\PC\root\cimv2:Win32_DiskDrive.DeviceID="\\.\PHYSICALDRIVE0""
Dependent="\\PC\root\cimv2:Win32_DiskPartition.DeviceID="Disk #0, Partition #0""

==>

因此,使用"Where AssocClass = Win32_DiskDriveToDiskPartition"子句,您可以查询ASSOCIATORS OF

string query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + dd_ID
                    + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";

string query = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + pp_ID
                    + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";

这里,关于上面的场景(见wmic输出):

  • dd_ID也可以
    • "\\.\PHYSICALDRIVE0"
    • "\\.\PHYSICALDRIVE1"(当然还有两件商品收藏)和
  • pp_ID也可以
    • "Disk #0, Partition #0"
    • "Disk #1, Partition #0"
    • "Disk #1, Partition #1"

我已在VBScript中的所有数据组合中对上述查询进行了测试,并希望它也可以在c#中运行(完全可能需要在c#中转义反斜杠。)< / p>