Question

First of all I wanna thank you for making time to read my post. I need a Visual basic or a VBSCript code that can detect if a specific USB is plugged. I have therse infos:

VID_0DF7 PID_0620

My code do not want to work :( I dont know how to make it to read only a specific VID and Pid :( Please dont thumb my post down only because I do not know how to do something. I found many examples on the internet but actualy for telling what is the PID and the VID for All plugged devices...so...i do not need them...

My code:

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colDevices = objWMIService.ExecQuery _
    ("Select * From Win32_USBControllerDevice")

For Each objDevice in colDevices
    strDeviceName = objDevice.Dependent
    strQuotes = Chr(34)
    strDeviceName = Replace(strDeviceName, strQuotes, "")
    arrDeviceNames = Split(strDeviceName, "=")
    strDeviceName = arrDeviceNames(1)
    Set colUSBDevices = objWMIService.ExecQuery _
        ("Select * From Win32_PnPEntity Where DeviceID = '" & strDeviceName & "'")
    For Each objUSBDevice in colUSBDevices
        Wscript.Echo objUSBDevice.Description
    Next    
Next

Thank you!

Was it helpful?

Solution

Something like this should work:

Set wmi = GetObject("winmgmts://./root/cimv2")

vid = "VID_0DF7"
pid = "PID_0620"

For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice")
  If InStr(d.Dependent, vid & "&" & pid) > 0 Then
    WScript.Echo wmi.Get(d.Dependent).Description
  End If
Next

If you want a notification when there's no device matching your criteria, you cannot implement an Else branch inside the loop. A nested Else would fire for each device that doesn't match the criteria, whereas you want a notification only if none of the devices match the criteria. Use a boolean value that you change to True when you find a matching device:

found = False
For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice")
  If InStr(d.Dependent, vid & "&" & pid) > 0 Then
    WScript.Echo wmi.Get(d.Dependent).Description
    found = True
  End If
Next

If Not found Then WScript.Echo "USB not found."
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top