Watching for any USB device plugged in -- WMI

Recommended Posts

bartekd 0

bartekd 0

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 ****#AutoIt3Wrapper_UseUpx=n#AutoIt3Wrapper_Res_requestedExecutionLevel=asInvoker#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 ----------------Sleep(111111);- The event that is called upon detecting a USB storage device.Func sink_OnObjectReady($objObject,$objAsyncContext)Local$choiceIf$objObject.TargetInstance.DriveType=2Then;- TargetIstance.DriveType = 2 means a Removable drive.SelectCase$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)CaseElseMsgBox(0,"","WTF?")EndSelectEndIfEndFunc