Finding USB drive letter with VBScript

前端 未结 2 949
眼角桃花
眼角桃花 2020-12-11 13:31

I found this script on http://network-blog.lan-secure.com/2008/03/usb-detection-using-wmi-script.html

 strComputer = \".\" \'(Any computer name or address)
          


        
相关标签:
2条回答
  • 2020-12-11 14:16

    colDrives is a collection of all connected drives, not last connected only. Should be:

    strDriveLetter = ""
    For Each objDrive in colDrives
      strDriveLetter = strDriveLetter  & objDrive.DeviceID
    Next
    
    0 讨论(0)
  • 2020-12-11 14:17

    This is extremely difficult to do. Most useful drive information is pulled from the Win32_LogicalDrive class. Unfortunately, removable drives often do not populate this class with much information about the drive. Useful properties such as DeviceID and PNPDeviceID are most often left empty. The next best thing to do is iterate the Win32_LogicalDisk class for instances that are removable disks. In keeping with your event-driven approach, that would look something like this.

    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
    

    Of course, this will only work if the inserted drive is the only removable disk on the system. You could work around this limitation by grabbing all of the drive letters when your script starts and comparing them when a drive is inserted, however, that approach isn't bulletproof either. Changing the drive letter assignments of any other drives would cause your script to return invalid information.

    0 讨论(0)
提交回复
热议问题