我在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的命令行扫描程序,以自动扫描Insertion上的驱动器。请指导!
答案 0 :(得分: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
当然,这只有在插入的驱动器是系统上唯一的可移动磁盘时才有效。您可以通过在脚本启动时抓取所有驱动器号并在插入驱动器时比较它们来解决此限制,但是,这种方法也不是防弹的。更改任何其他驱动器的驱动器号分配将导致脚本返回无效信息。
答案 1 :(得分:0)
colDrives 是所有连接的驱动器的集合,而不是仅限上次连接。 应该是:
strDriveLetter = ""
For Each objDrive in colDrives
strDriveLetter = strDriveLetter & objDrive.DeviceID
Next