【问题标题】:Finding USB drive letter with VBScript使用 VBScript 查找 USB 驱动器号
【发布时间】:2012-01-06 20:16:49
【问题描述】:

我在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 的命令行扫描程序以在插入时自动扫描驱动器。请指导!

【问题讨论】:

    标签: windows vbscript wmi usb-drive


    【解决方案1】:

    这是极难做到的。最有用的驱动器信息来自 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
    

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

    【讨论】:

      【解决方案2】:

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

      strDriveLetter = ""
      For Each objDrive in colDrives
        strDriveLetter = strDriveLetter  & objDrive.DeviceID
      Next
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-02
        • 1970-01-01
        • 2011-07-12
        • 2020-03-19
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        相关资源
        最近更新 更多