1

我在http://network-blog.lan-secure.com/2008/03/usb-detection-using-wmi-script.html上找到了这个脚本

 strComputer = "." '(Any computer name or address)
 Set wmi = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
 Set wmiEvent = wmi.ExecNotificationQuery("select * from __InstanceOperationEvent within 1 where TargetInstance ISA 'Win32_PnPEntity' and TargetInstance.Description='USB Mass Storage Device'")
 While True
 Set usb = wmiEvent.NextEvent()
 Select Case usb.Path_.Class
 Case "__InstanceCreationEvent" WScript.Echo("USB device found")
 Case "__InstanceDeletionEvent" WScript.Echo("USB device removed")
 Case "__InstanceModificationEvent" WScript.Echo("USB device modified")
 End Select
 Wend

这个脚本在我需要的旁边。它检测 USB 驱动器的插入。如何修改它以找到USB驱动器的驱动器号?如果我得到驱动器号,那么在插入时而不是回显“找到 USB 设备”,我将能够运行 Avast Antivirus 的命令行扫描程序以在插入时自动扫描驱动器。请指导!

4

2 回答 2

3

这是极难做到的。最有用的驱动器信息来自 Win32_LogicalDrive 类。不幸的是,可移动驱动器通常不会在此类中填充有关驱动器的大量信息。有用的属性,如 DeviceID 和 PNPDeviceID 通常是空的。下一个最好的事情是为可移动磁盘的实例迭代 Win32_LogicalDisk 类。与您的事件驱动方法保持一致,这看起来像这样。

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set wmiEvent = objWMIService.ExecNotificationQuery( _
    "Select * From __InstanceCreationEvent Within 1" & _
        " Where TargetInstance ISA 'Win32_PnPEntity' and" & _
            " TargetInstance.Description='USB Mass Storage Device'")

While True
    Set objEvent = wmiEvent.NextEvent()
    Set objUSB = objEvent.TargetInstance
    strName = objUSB.Name
    strDeviceID = objUSB.DeviceID
    Set objUSB = Nothing

    Set colDrives = objWMIService.ExecQuery( _
        "Select * From Win32_LogicalDisk Where DriveType = 2")

    For Each objDrive in colDrives
        strDriveLetter = objDrive.DeviceID
    Next
    Set colDrives = Nothing

    WScript.Echo strName & " was mounted as " & strDriveLetter
Wend
Set wmiEvent = Nothing
Set objWMIService = Nothing

当然,这只有在插入的驱动器是系统上唯一的可移动磁盘时才有效。您可以通过在脚本启动时获取所有驱动器号并在插入驱动器时比较它们来解决此限制,但是,这种方法也不是万无一失的。更改任何其他驱动器的驱动器号分配会导致您的脚本返回无效信息。

于 2011-11-26T18:47:20.237 回答
0

colDrives所有已连接驱动器的集合,而不仅仅是最后连接的。应该:

strDriveLetter = ""
For Each objDrive in colDrives
  strDriveLetter = strDriveLetter  & objDrive.DeviceID
Next
于 2014-07-27T16:46:41.077 回答