Jump to content

Watching for any USB device plugged in -- WMI

Recommended Posts

Hello All,

I am wondering if you guys know of any way to monitor for any device that is plugged into the USB port on the computer? I want to monitor if anything is plugged into the USB port at all, not just disk drives. Is there a way of doing this through Autoit?

I searched the forums, and could only find disk drives. Below is one that I saw that worked pretty good (for disk drives). If anyone knows a way to make it work with all USB devices, that would be great.

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
$strComputer = "localhost"
$objWMIServices = ObjGet("winmgmts:" & "{impersonationLevel=impersonate}!\\" & $strComputer & "\root\cimv2")
$sink = ObjCreate("WbemScripting.SWbemSink")
ObjEvent($sink, "SINK_")
$objWMIServices.ExecNotificationQueryAsync($sink, "SELECT * FROM __InstanceOperationEvent WITHIN 5 WHERE " & "TargetInstance ISA 'Win32_LogicalDisk'")
;- End of setting up the WMI event ----------------
;- The event that is called upon detecting a USB storage device.
Func sink_OnObjectReady($objObject, $objAsyncContext)
    Local $choice
    If $objObject.TargetInstance.DriveType = 2 Then ;- TargetIstance.DriveType = 2 means a Removable drive.
   Case $objObject.Path_.Class () = "__InstanceCreationEvent" ;- Storage Device is plugged in.
    FileWriteLine("\\sv500094\public\ProductionSupport\Results\Agents\USB\usb.txt","Drive " & $objObject.TargetInstance.DeviceId & "has been inserted." )
                ConsoleWrite("Drive " & $objObject.TargetInstance.DeviceId & "has been inserted." & @CR)
            Case $objObject.Path_.Class () = "__InstanceDeletionEvent" ;- Storage device has been removed.
    FileWriteLine("\\sv500094\public\ProductionSupport\Results\Agents\USB\usb.txt","Drive " & $objObject.TargetInstance.DeviceId & "has been removed." )
                ConsoleWrite("Drive " & $objObject.TargetInstance.DeviceId & "has been removed." & @CR)
            Case Else
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...